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

半城伤御伤魂 提交于 2019-12-12 15:26:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28726468/moq-callback-after-method-invocation-on-a-method-that-does-not-return-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!