Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pester version 5 pass variables to test

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading