Moq: Callback after method invocation on a method that does not return a value

c#, moq, unit-testing

Solution

It's not possible.

The return value of `Callback` is IReturnsThrows, which is a combination of the `IReturns` interface with `Returns` methods, and `IThrows` interface with `Throws` methods. You can follow a `Returns` with a `Callback` because the return value of `Returns` is `IReturnResult` which implements `ICallback`.

What exactly are you trying to accomplish? The callbacks in your example don't really occur before and after the method are called, they are simply executed in order as steps when the method is called. Your before callback is executed before the return value is computed, then your after callback is done after that. There is no point to doing two callbacks in a row since you can just combine them into a single callback.

Problem

I am currently using the Moq library for unit testing. Moq gives me the ability to register callbacks before and after method invocation on a mocked object like so: ``` Mock<IMyClass> mock = new Mock<IMyClass>(); mock.Setup(o => o.MyMethod()) .Callback(() => Console.WriteLine("BEFORE!")) .Returns(true) .Callback(() => Console.WriteLine("AFTER!")); ``` However, if MyMethod does not return a value (i.e. it has a void return type), then I can only setup a single Callback like so: ``` mock.Setup(o => o.MyMethod()) .Callback(() => Console.WriteLine("BEFORE!")); ``` As noted in the code, this callback happens BEFORE the method is invoked. There don't seem to be any other options for specifying a second callback for after the method is invoked. Is this possible? There doesn't seem to be anything in the documentation about it. Am I missing something?

Original source