Should
Overview​
Pester includes a comprehensive set of assertions that you can use to either fail or pass a test. In fact, Pester v6 actually includes two sets of assertions:
- All new
Should-*assertions introduced in Pester v6, e.g.Should-BeString,Should-BeTrueetc. - The
Shouldcommand known from previous version of Pester, invoked using parameter sets likeShould -Be,Should -BeTrueetc.
Both types of assertions are supported side-by-side in Pester v6, but we recommend you try out and migrate to the newer assertions.
Should-* assertions (v6)​
Pester v6 comes with a new set of Should-* assertions that have been built from the ground up.
If you've previously tested the Assert-module, these will be familiar.
Check out Command Reference in the sidebar to read more about the new assertions, e.g. Should-BeString.
These new assertions are split into these categories based on their usage:
- Value
- Collection
- Generic
- Combinator
Each of these categories treats $Actual and $Expected values differently, to provide a consistent behavior when using the | syntax.
Value vs. Collection assertions​
The $Actual value can be provided by two syntaxes, either by pipeline (|) or by parameter (-Actual):
1 | Should-Be -Expected 1
Should-Be -Actual 1 -Expected 1
Using pipeline syntax​
When using the pipeline syntax, PowerShell unwraps the input and we lose the type of the collection on the left side. We are provided with a collection that can be either $null, empty or have items. Notably, we cannot distinguish between a single value being provided, and an array of single item:
1 | Should-Be
@(1) | Should-Be
These will both be received by the assertion as @(1).
For this reason a value assertion will handle this as 1, but a collection assertion will handle this input as @(1).
Another special case is @(). A value assertion will handle it as $null, but a collection assertion will handle it as @().
$null remains $null in both cases.
# Should-Be is a value assertion:
1 | Should-Be -Expected 1
@(1) | Should-Be -Expected 1
$null | Should-Be -Expected $null
@() | Should-Be -Expected $null # @() is handled as $null by a value assertion
# This fails, because -Expected does not allow collections.
@() | Should-Be -Expected @()
# Should-BeCollection is a collection assertion:
1 | Should-BeCollection -Expected @(1)
@(1) | Should-BeCollection -Expected @(1)
@() | Should-BeCollection -Expected @()
# This fails, because -Expected requires a collection.
$null | Should-BeCollection -Expected $null
Using the -Actual syntax​
The value provided to -Actual is always exactly the same as provided.
Should-Be -Actual 1 -Expected 1
# This fails, Actual is collection, while expected is int.
Should-Be -Actual @(1) -Expected 1
Value assertions​
Generic value assertions​
Generic value assertions, such as Should-Be, are for asserting on a single value. They behave quite similar to PowerShell operators, e.g. Should-Be maps to -eq.
The $Expected accepts any input that is not a collection.
The type of $Expected determines the type to be used for the comparison.
$Actual is automatically converted to that type.
1 | Should-Be -Expected $true
Get-Process -Name Idle | Should-Be -Expected "System.Diagnostics.Process (Idle)"
The assertions in the above examples will both pass:
1converts tobool-value as$true, which is the expected value.Get-Processretrieves theIdleprocess (on Windows). This process object gets converted tostringwhich is equal to the expected value.
Type specific value assertions​
Type specific assertions are for asserting on a single value of a given type like boolean.
These assertions take the advantage of being more specialized to provide a type specific functionality, such as Should-BeString -IgnoreWhitespace.
$Expectedaccepts input that has the same type as the assertion type. E.g.Should-BeString -Expected "my string".$Actualaccepts input that has the same type as the assertion type. The input is not converted to the destination type unless the assertion specifies it, e.g.Should-BeFalsywill convert tobool.
Collection assertions​
Collection assertions operate on the whole collection provided to $Actual instead of unwrapping it to a single value. Use them whenever you want to assert on multiple items at once.
Generic collection assertions​
Should-BeCollection compares two collections by first comparing their size, and then comparing each item. The $Expected value must be a collection.
1, 2, 3 | Should-BeCollection @(1, 2, 3)
@(1) | Should-BeCollection @(1)
# This fails, the collections have different sizes.
1, 2, 3, 4 | Should-BeCollection @(1, 2, 3)
You can also assert on the size of a collection without comparing items, by using -Count:
1, 2, 3 | Should-BeCollection -Count 3
Should-ContainCollection and Should-NotContainCollection check whether the expected items are (or are not) present in the provided collection, in order.
1, 2, 3 | Should-ContainCollection @(1, 2)
1, 2, 3 | Should-NotContainCollection @(3, 4)
Combinator assertions​
Combinator assertions take a -FilterScript and run it against every item in the collection. The filter can be a plain PowerShell expression or another Should-* assertion.
Should-All passes when every item matches the filter:
1, 2, 3 | Should-All { $_ -gt 0 }
1, 2, 3 | Should-All { $_ | Should-BeGreaterThan 0 }
Should-Any passes when at least one item matches the filter:
1, 2, 3 | Should-Any { $_ -gt 2 }
1, 2, 3 | Should-Any { $_ | Should-BeGreaterThan 2 }
Assertion reference​
All Should-* assertions are listed below, grouped by the kind of check they perform. Follow a link to see the full syntax, parameters, and examples in the Command Reference.
General​
Should-Be— Compares the expected value to the actual value to see if they are equal.Should-NotBe— Compares the expected value to the actual value to see if they are not equal.Should-BeGreaterThan— Asserts that the actual value is greater than the expected value.Should-BeGreaterThanOrEqual— Asserts that the actual value is greater than or equal to the expected value.Should-BeLessThan— Asserts that the actual value is less than the expected value.Should-BeLessThanOrEqual— Asserts that the actual value is less than or equal to the expected value.Should-BeNull— Asserts that the input is$null.Should-NotBeNull— Asserts that the input is not$null.Should-BeSame— Asserts that the actual value is the same instance as the expected value.Should-NotBeSame— Asserts that the actual value is not the same instance as the expected value.Should-HaveType— Asserts that the input is of the expected type.Should-NotHaveType— Asserts that the input is not of the expected type.
Boolean​
Should-BeTrue— Asserts that the actual value is$true.Should-BeFalse— Asserts that the actual value is$false.Should-BeTruthy— Asserts that the actual value is truthy.Should-BeFalsy— Asserts that the actual value is falsy (0,"",$nullor@()).
String​
Should-BeString— Asserts that the actual value is equal to the expected string. Supports-CaseSensitive,-IgnoreWhitespaceand-TrimWhitespace.Should-NotBeString— Asserts that the actual value is not equal to the expected string.Should-BeEmptyString— Asserts that the input is an empty string.Should-NotBeEmptyString— Asserts that the input is a string that is not$nullor empty.Should-NotBeWhiteSpaceString— Asserts that the input is a string that is not$null, empty, or whitespace only.Should-BeLikeString— Asserts that the actual value matches the expected wildcard pattern.Should-NotBeLikeString— Asserts that the actual value does not match the expected wildcard pattern.Should-MatchString— Asserts that the actual value matches the expected regular expression.Should-NotMatchString— Asserts that the actual value does not match the expected regular expression.
Collection​
Should-BeCollection— Compares collections for equality, by comparing their size and each item.Should-ContainCollection— Asserts that the expected items are present in the provided collection, in order.Should-NotContainCollection— Asserts that the expected items are not present in the provided collection.Should-All— Asserts that every item in the collection matches a filter.Should-Any— Asserts that at least one item in the collection matches a filter.
Equivalency​
Should-BeEquivalent— Recursively compares two objects for equivalency, by comparing their properties.
DateTime and TimeSpan​
Should-BeBefore— Asserts that the actual[datetime]is before the expected[datetime].Should-BeAfter— Asserts that the actual[datetime]is after the expected[datetime].Should-BeFasterThan— Asserts that the provided[timespan]or[scriptblock]is faster than the expected[timespan].Should-BeSlowerThan— Asserts that the provided[timespan]or[scriptblock]is slower than the expected[timespan].
Exception​
Should-Throw— Asserts that a script block throws an exception.
Mock​
Should-Invoke— Asserts that a mocked command was called the expected number of times. See Mocking.Should-NotInvoke— Asserts that a mocked command was not called. See Mocking.
Command parameters​
Should-HaveParameter— Asserts that a command has the expected parameter, and optionally checks its type, default value, aliases, parameter set, mandatory status, and argument completer.Should-NotHaveParameter— Asserts that a command does not have the given parameter.
Choosing your assertion syntax​
The classic Should -Be assertions still ship and still work, and the new Should-* assertions sit alongside them. You can adopt them one test at a time, or mix both styles in the same suite while you migrate.
When you are ready to commit to the new style, switch the old syntax off so it can't be used by accident:
$config = New-PesterConfiguration
$config.Should.DisableV5 = $true
With Should.DisableV5 enabled, using the classic Should -Be syntax throws, pointing you at the new command:
Pester Should -Be syntax is disabled. Use Should-Be (without space), or enable it by setting: $PesterPreference.Should.DisableV5 = $false
Should (v4/v5)​
Should is used to do an assertion that fails or passes the test.
An example of assertion is comparing two strings in case insensitive manner:
"Pester is bad." | Should -Be "Pester is awesome!"
Which throws an exception with this text to fail the test:
Expected strings to be the same, but they were different.
Expected length: 18
Actual length: 14
Strings differ at index 10.
Expected: 'Pester is awesome!'
But was: 'Pester is bad.'
----------^
Other assertion types can be found in Assertion Reference.
Collect all Should failures​
Should can now be configured to continue on failure. This will report the error to Pester, but won't fail the test immediately. Instead, all the Should failures are collected and reported at the end of the test. This allows you to put multiple assertions into one It and still get complete information on failure.
This new Should behavior is opt-in and can be enabled via Should.ErrorAction = 'Continue' on the configuration object or via $PesterPreference. The new Should-* assertions honor this setting too, so you can collect multiple failures whichever syntax you use.
BeforeAll {
function Get-User {
@{
Name = "Jakub"
Age = 31
}
}
}
Describe "describe" {
It "user" {
$user = Get-User
$user | Should -Not -BeNullOrEmpty -ErrorAction Stop
$user.Name | Should -Be "Tomas"
$user.Age | Should -Be 27
}
}
Running tests from 1 files.
Running tests from 'C:\t\describe.Tests.ps1'
Describing describe
[-] user 124ms
[0] Expected strings to be the same, but they were different.
String lengths are both 5.
Strings differ at index 0.
Expected: 'Tomas'
But was: 'Jakub'
^
at $user.Name | Should -Be "Tomas", C:\t\describe.Tests.ps1:15
[1] Expected 27, but got 31.
at $user.Age | Should -Be 27, C:\t\describe.Tests.ps1:16
Tests completed in 286ms
Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
This allows you to check complex objects easily without writing It for each of the properties that you want to test. You can also use -ErrorAction Stop to force a failure when a pre-condition is not met. In our case if $user was null, there would be no point in testing the object further and we would fail the test immediately.