-
Notifications
You must be signed in to change notification settings - Fork 5
Importing Scripts
So far the examples have just shown a simple calculation. In practice, you will need to import at least one other script - the Script Under Test.
Let's assume you have a Calculator.ps1
script to test:
function Add-Numbers {
param ([int] $x, [int] $y)
$x + $y
}
You would probably write your test cases in Calculator.Tests.ps1
:
Describing "Calculator" {
Given "two numbers" {
It "Adds" {
Add-Numbers 1 1 | Should Be 2
}
}
}
If you run this, you will likely find that Add-Numbers is undefined, (unless you ran Calculator.ps1 and put Add-Numbers in your global scope). Whoops, we forgot to import the script. To import a script, dot-source it. PSate provides a very handy $TestScriptPath
variable that is the path to the current test script.
# import the script
. $TestScriptPath\Calculator.ps1
Describing "Calculator" {
Given "two numbers" {
It "Adds" {
Add-Numbers 1 1 | Should Be 2
}
}
}
At this point, your tests will run fine from Invoke-Tests (see Running Tests with Invoke-Tests), but will fail when the tests are run directly. That's because $TestScriptPath isn't defined at the top level. Fortunately, we can easily wrap this with a TestScope block:
TestScope "Calculator.ps1" {
# import the script
. $TestScriptPath\Calculator.ps1
Describing "Calculator" {
Given "two numbers" {
It "Adds" {
Add-Numbers 1 1 | Should Be 2
}
}
}
}
Now that we imported the script from within a PSate test block, the $TestScriptPath
variable is defined for us. Note that you could have used $TestScriptPath from within the Describing block or any other block.