Applies to Pester 3.4.0
Like any Windows PowerShell script, a script that contains Pester tests can include parameters. It’s easy enough to run the script and pass parameters and values in the usual way.
But, when you use Invoke-Pester to run the script, you need to pass the parameters in a hash table. This blog explains how to do it.
This post is the third in a series about how to run Pester tests. See also, How to Run a Pester Test and Invoke-Pester: Running Selected Tests.
See the posts in this Pester series:
————————–
To use Invoke-Pester to pass parameters to a script, use a command like this one:
Invoke-Pester -Script @{Path='C:\Tests\MyTests.Tests.ps1';Parameters=@{Name='Pester';Version='3.4.0'}} |
Or, this one:
Invoke-Pester -Script @{Path = 'C:\Tests\MyTests.Tests.ps1'; Arguments = 'Pester', '3.4.0'} |
The Script parameter of Invoke-Pester typically takes a array of paths, either paths to a directory or to scripts that typically contain Pester tests, or both.
But, it can also take a hash table. One hint is that Script parameter type is [System.Object[]], not [System.String[]].
Here are hash table keys:
Invoke-Pester -Script @{Path='C:\Tests\MyTests.Tests.ps1'} |
Invoke-Pester -Script @{Path = 'C:\Tests\MyTests.Tests.ps1'; Parameters = @{Name = 'Pester'; Version = '3.4.0'}} |
Invoke-Pester -Script @{Path = 'C:\Tests\MyTests.Tests.ps1'; Arguments = 'Pester', '3.4.0'} |
Invoke-Pester splats the parameters and arguments to the scripts as it calls them.
Typically, the Path value in the hash table resolves to a particular script that takes the specified named and/or positional parameters. But, when you pass parameters to a script that has no parameters, the extraneous parameters are ignored, so you can use a directory value effectively.
For example, this command passes the ComputerName to one .Tests.ps1 file, but the command runs all .Tests.ps1 files in the directory and its subdirectories.
Invoke-Pester -Script @{Path = 'C:\Tests\MyTests'; Parameters = @{ComputerName = 'localhost'}} |
Of course, this strategy is error-prone and will not work when more than one of the scripts being run takes different parameters, so it’s probably not advisable.
But, it’s easy enough to pass parameters to a Pester test. Pester really is amazing!
Learning Pester? Check out Real-World Test-Driven Development with Pester. The code and slides are in Github at https://github.com/juneb/PesterTDD.
June Blender is a technology evangelist at SAPIEN Technologies, Inc. You can reach her at juneb@sapien.com or follow her on Twitter at @juneb_get_help.