powershell - Pester 版本 5 传递变量进行测试

标签 powershell pester

我不知道如何将参数传递给我的 Pester v5 测试。

这是我在 Pester 中的配置文件:

Import-Module Pester -Force
$testFile = 'C:\PowerShell\MyTests\'

$tr = 'C:\PowerShell\MyTests\TEST-MyTests.xml'

$configuration = [PesterConfiguration]@{
  PassThru = $true
  Run = @{
     Path = $testFile
  }
  Output = @{
     Verbosity = 'Detailed'
  }

  TestResult = @{
     Enabled = $true
     OutputFormat = "NUnitXml"
     OutputPath   = $tr
  }
}       

Invoke-Pester -Configuration $configuration

这是我的简单测试,我需要将值传递给变量 testUrl,该值现在是硬编码的:

BeforeAll {
    $tesUrl = "https://test.com/"

}
Describe "Status of my testsystem" {
    It "Should be http code 200" {
        $request = [System.Net.WebRequest]::Create($tesUrl)
        $request.Method = "HEAD"
        $response = $request.GetResponse()
        $response.StatusCode | Should -Be 200
    }
}

如何将参数传递到 Pester 测试,以便我可以在多个环境中运行测试?

最佳答案

根据此处的文档:https://pester.dev/docs/usage/data-driven-tests#providing-external-data-to-tests

您需要使用 New-PesterContainer 创建一个包含您要使用的测试数据的对象,然后将其添加到 Run.Container 下的 Pester 配置对象中:

Import-Module Pester -Force
$testFile = 'C:\PowerShell\MyTests\'

$tr = 'C:\PowerShell\MyTests\TEST-MyTests.xml'

$Container = New-PesterContainer -Path $testFile -Data @{ 
   testurl  = 'https://urlyouwanttotest.com/'
}

$configuration = [PesterConfiguration]@{
  Run = @{
   PassThru = $true
   Container = $Container
  }
  Output = @{
     Verbosity = 'Detailed'
  }

  TestResult = @{
     Enabled = $true
     OutputFormat = "NUnitXml"
     OutputPath   = $tr
     }
  }       

  Invoke-Pester -Configuration $configuration

您的测试文件需要包含一个 param block :

param(
   [string]
   $testurl
)

BeforeAll {
    $tesUrl = $testUrl
}

Describe "Status of my testsystem" {
    It "Should be http code 200" {
        $request = [System.Net.WebRequest]::Create($tesUrl)
        $request.Method = "HEAD"
        $response = $request.GetResponse()
        $response.StatusCode | Should -Be 200
    }
}

关于powershell - Pester 版本 5 传递变量进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75208718/

相关文章:

powershell - Pester 示例脚本在 Windows 10 上获取 "-Be is not a valid Should operator",在 Ubuntu 上运行良好

linux - Powershell 无法在 VSCode Linux 上找到类型 [Pester.OutputTypes]

powershell - 如何正确模拟我的函数以使用 Pester 返回自定义属性?

powershell - 解析大型文本文件最终导致内存和性能问题

powershell - 使用 `pester` 测试 `pester` 版本

powershell - 以递归方式复制不包含子目录及其内容的目录

string - Powershell-从字符串变量中提取第一个和第三个元素

powershell - 如何以编程方式设置 MSMQ 队列的所有者?

带有 Pester 测试的 PowerShell - 未找到测试文件且未提供脚本 block

powershell - 确定PSCustomObject的数组是否包含具有属性值的实例