-
Notifications
You must be signed in to change notification settings - Fork 7
Should Command
Jon Wagner edited this page Feb 10, 2015
·
2 revisions
The Should command expects a value as pipeline input, and has a flexible syntax for the assertion:
actual | Should [not] [comparison] [expected] [and | -test]
The comparisons are:
- Be - the input is tested against the expected value, with some additional options See Should Be See Get-Help ShouldBe for details.
- Equal - the input is tested against the expected value. Arrays are tested for element equality.
- Contain - the input is a collection, and must contain the given value. If the operand is a collection, its presence is tested as a whole.
- ContainAll - the input is a collection, and must contain all of the given values. The operand should be a collection.
- ContainNone - the input is a collection, and must contain none of the given values. The operand should be a collection.
- Match - the input is a string, and must contain the given pattern.
- Count - the input is a collection, and must contain the given number of elements.
- Throw - the input is a script block, which is executed and the exception is tested. See Testing Exceptions.
- Exist - the input is a Path, and Test-Path is called to check its existence.
- ContainContent - the input is a Path, whose Get-Content is must contain a pattern.
- [ScriptBlock] - the scriptblock is executed. The first parameter is the input. See Testing with ScriptBlocks.
If the command ends with 'and', then the inputs are copied to the output stream for further testing or operation. See Chaining Assertions with And.
If the command ends with '-test', then the result of the test is output to the stream, and an exception is not thrown. See Testing without Throwing with -Test.
For details on the individual operations, use Get-Help Should*
Examples:
$x = 1
$x | Should Be 1
$x | Should Not Be 2
$x | Should Equal 1
$s = "hi, bob"
$s | Should Match "^hi"
$arr = @(1,2,3)
$arr | Should Be @(1,2,3)
$arr | Should Contain 2
$arr | Should Count 3
$hash = @{x=4;y=3}
$hash | Should Be @{x=4;y=3}
$hash | Should Contain 'x'
$hash | Should Count 2
{ CallScaryFunction } | Should Throw
{ throw "whoops" } | Should Throw "whoops"
Set-Content 'c:\temp' 'hello, world'
'c:\temp' | Should Exist
'c:\temp' | Should ContainContent 'world$'
$x | Should { param ($i) $i -eq 1 }