I'm stuck on how to pass parameters to my Pester v5 tests.
This is my config-file in 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
This is my simple test where I need to pass value to variable testUrl, this value is now hard coded:
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
}
}
How can i pass parameters in to the Pester-test so I can run the test for several environments?
CodePudding user response:
Per the documentation here: https://pester.dev/docs/usage/data-driven-tests#providing-external-data-to-tests
You need to use New-PesterContainer
to create an object with the test data you want to use, and then add that to your Pester configuration object under Run.Container
:
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
Your test file then needs to include a 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
}
}