简体   繁体   中英

How to 'get arguments for calls made on' a Mock in Pester (or otherwise generate a helpful message containing actual and expected values)?

While there are many examples of using Pester to Assert a Mock , I am unable to find good (or any) examples on how to use Pester to get parameters made upon a Mock; this is useful to get a meaningful error message instead of a generic message of so-so usefulness:

Expected Invoke-XYZ to be called at least 1 times but was called 0 times

Thanks, and obviously; might as well be a "didn't work" SO question.

In RhinoMocks + NUnit (C#), for example, one might use code similar to the following to assert that the mock was called and the arguments match some criteria. If the call was made and the arguments do not match, then a useful assertion message is displayed:

var actual = mock.GetArgumentsForCallsMadeOn(m => ..);
Assert.That(actual, Is.EqualTo(expected));

How can the same (or similar) be done in Pester?

The goal is to make failing mock assertions result in useful error messages as to what particular parameter failed the expectations, and with what value(s).

PowerShell is 5.1 and Pester is 4.8.1.

I have the same issue/question about Pester testing with parameter checks; it's always been hard to track down which parameter may have failed a given -ParameterFilter expression.

It's been raised in a couple of GitHub issues:

  1. https://github.com/pester/Pester/issues/376
  2. https://github.com/pester/Pester/issues/1160

But it doesn't seem like there was any resolution or consensus yet. I would try to add to the conversation there if you can.

One user talked about making a Verify function that is called within the Assert-MockCalled call:

It 'multiple expressions, second line' {
    Assert-MockCalled f 1 {
        ($a -eq 1 | Verify) -and
        ($b -eq 1 | Verify) -and
        ($b-1 -eq $a | Verify)
    }
}

which gave better output, but was a hacky/verbose way of getting around this.

Personally, my workaround has been to write multiple Assert-MockCalled statements, each with a -ParameterFilter expression that checks only one parameter, so that I can know which parameter failed based on which Assert-MockCalled statement failed. But, this approach does not work so well if, say, the mock is called multiple times within the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM