MOQ: what parameter was passed to a mocked function?

by EvanJPalmer

I came across an awesome feature of MOQ today.

I needed to see what parameter was passed to my mocked function in order to see if my LINQ was behaving correctly.

I couldn’t just test the return value of the function I was testing, because the value I was interested in was lost due to it being passed to an invocation of a method.

Enter MOQ callbacks.

According to the docs (https://code.google.com/p/moq/wiki/QuickStart):

// access invocation arguments
mock.Setup(foo => foo.Execute(It.IsAny<string>()))
    .Returns(true)
    .Callback((string s) => calls.Add(s));

Which basically means, we can pass a lambda to the CallBack method of the mocked function that matches the parameter we expect. We can now access this in the test and store it to a local variable (or do anything else to it progammatically).

Then assert it!

So sweet!

Advertisements