c# - NSubstitute:能够在没有返回类型的模拟方法中设置引用对象

标签 c# .net inversion-of-control nsubstitute

我有一个带有以下声明的接口(interface):

void MapServiceMessages(IEnumerable<ServiceMessage> serviceMessages, List<Message> responseMessages);

我想模拟这个方法,我发送一个返回消息类型列表的服务消息列表。既然它是 void 类型那么我怎么能模拟这个方法。

我不想更改我的声明和定义。

当然,我可以选择将 void 更改为 List,然后使用 (...).Returns(mychoiceofmessages)...

我想与社区核实他们是否遇到过这样的问题和更好的解决方案。

谢谢,

最佳答案

来自 NSubstitute callbacks 上的文档

Returns() can be used to get callbacks for members that return a value, but for void members we need a different technique, because we can’t call a method on a void return. For these cases we can use the When..Do syntax

public interface IFoo {
    void SayHello(string to);
}
[Test]
public void SayHello() {
    var counter = 0;
    var foo = Substitute.For<IFoo>();
    foo.When(x => x.SayHello("World"))
        .Do(x => counter++);

    foo.SayHello("World");
    foo.SayHello("World");
    Assert.AreEqual(2, counter);
}

关于c# - NSubstitute:能够在没有返回类型的模拟方法中设置引用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29785843/

相关文章:

c# - CaSTLe 温莎 FirstInterface().Configure(c=> c.LifeStyle.PerWebRequest)

c# - 为什么 String S =new string() 在 C# 中无效

c# - 如何将两个序列合并为一个?

c# - 是什么决定了 WPF 中文本的修剪方式

c# - 从数据库自动更新

c# - 如何获取基类的公共(public)静态方法?

c# - 依赖注入(inject)初始化

c# - 如何解码嵌入在 json 字符串中的 HTML 编码字符

c# - Linq 实体与 WCF

c#-4.0 - 在传递构造函数参数时在 LightInject 中注册服务时指定生命周期?