Moq:在不返回值的方法上调用方法后的回调 [英] Moq: Callback after method invocation on a method that does not return a value

查看:44
本文介绍了Moq:在不返回值的方法上调用方法后的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Moq库进行单元测试. Moq使我能够在模拟对象上在方法调用之前 后注册回调,如下所示:

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!"));

但是,如果 MyMethod 不返回值(即它具有 void 返回类型),那么我只能像这样设置单个Callback:

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?

推荐答案

不可能.

Callback的返回值是IReturnsThrows,它是IReturns接口和Returns方法以及IThrows接口和Throws方法的组合.您可以在Returns后面加上Callback,因为Returns的返回值是IReturnResult,它实现了ICallback.

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.

您到底想完成什么?您的示例中的回调实际上并没有在调用该方法之前和之后发生,它们只是在调用该方法时按步骤顺序执行.您的before回调在计算返回值之前执行,然后在此之后执行after回调.连续进行两个回调是没有意义的,因为您可以将它们组合成一个回调.

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.

这篇关于Moq:在不返回值的方法上调用方法后的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆