Skip to content
Jon Wagner edited this page Mar 8, 2013 · 3 revisions

The Should Be Command

'Should Be' and 'Should Equal' are very similar, but Should Be supports a few more options.

actual | Should [not] Be [operator] value [and | -test]

By default, the operator is assumed to be -eq, but you can specify other operators instead, or use more readable forms:

  • EqualTo, -eq, eq
  • NotEqualTo, -ne, ne
  • GreaterThan, -gt, gt
  • GreaterThanOrEqualTo, -gte, gte
  • LessThan, -lt, lt
  • LessThanOrEqualTo, -lte, lte

Value is typically a constant, but can be many different things:

  • Constant or variable - performs the given operation test.
  • Array or hashtable - performs an equality test at the element level.
  • Null - equivalent to $null.
  • Empty - equivalent to '' or an empty array or hashtable.

Both and and -test are supported. See Chaining Assertions with And and Testing without Throwing with -Test.

Array Tests

When you pass an array of items to a pipe in PowerShell, it unrolls the array and passes each element individually. This causes a single-element array to be equivalent to the element itself. This happens so much (and often unexpectedly) in PowerShell that Should Be honors the equivalence.

# identity as expected
1 | should be 1

# element equal to single-element array
1 | should be @(,1)
@(,1) | should be 1

# array equivalence is by count, then positional-equivalence
@() | should be @()
@(,1) | should be @(,1)
@(1,1) | should be @(1,1)
@(1,2) | should be @(1,2)
@(1,1) | should not be @(1,2)

# array length mismatch
@() | should not be 1
@() | should not be @(,1)
@() | should not be @(1,1)

1 | should not be @()
1 | should not be @(1,1)

@(,1) | should not be @()
@(,1) | should not be @(1,1)

@(1,1) | should not be @()
@(1,1) | should not be 1
@(1,1) | should not be @(,1)

# differentiating 1 from @(,1)
1 -is [array] | should be false
@(,1) -is [array] | should be true

In/NotIn

when a list/array of items is passed to Should Be In/NotIn, it will check each individual item for membership in the target list. For example:

(1) | Should Be In (1, 2, 3)
(1, 2) | Should Be In (1, 2, 3)
(1, 2, 4) | Should Not Be In (1, 2, 3)

If you need to test membership of a collection in a collection, wrap it in another array. Note that membership tests for objects uses an identity comparison.

# fails due to equality checks
,(1, 2) | Should Be In ((1, 2), (3, 4))

# passes because of object equality
$a = (1, 2)
,$a | Should Be In ($a, (3, 4))