github pester/Pester 4.8.0

latest releases: 6.0.0-alpha5, 6.0.0-alpha4, 6.0.0-alpha3...
5 years ago

What is new in 4.8.0?

Relaxing mocks

Mock now has two new parameters that allow you to remove types and validation from the function signature. This is useful especially when you have an external cmdlet that has strongly typed parameters but you have no way of constructing those parameters. In that case you can relax the type signature and provide any object that you like. In this silly example I remove the int type as well as the range validation, and provide a string instead.

function f (
    [ValidateRange(1,10)]
    [int] $Count) {
    $Count
}

Describe "Removing type" {
    Context "c" {
        It "does not work" {
            Mock f -MockWith { "this is count: $($Count)" }
            f "my value" | Should -Be "this is count: my value"
        }    
    }

    Context "c" {
        It "works" {
            Mock f `
                -MockWith { "this is count: $($Count)" } `
                -RemoveParameterType Count `
                -RemoveParameterValidation Count 
            
            f "my value" | Should -Be "this is count: my value"
        }    
    }
}

## output
# Describing Removing type
#
#  Context c
#    [-] does not work 159ms
#      FormatException: Input string was not in a correct format.
#      Cannot convert value "my value" to type "System.Int32"
#
#  Context c
#    [+] works 186ms

There is a limitation that you should be aware of: When defining multiple mocks that mock the same command you need to specify the Remove* parameters on the mock that is created first. That mock creates the mock bootstrap function and that is where the function signature is defined. Any subsequent definition will use the same bootstrap function. Notice the Context blocks in the example code, if you removed them the same Mock scope would be used for the whole Describe and the second example would not work because the non-relaxed mock bootstrap function would be used.

Many thanks to @renehernandez for implementing this!

Other fixes

Don't miss a new Pester release

NewReleases is sending notifications on new releases.