c# - Moq SetupSequence 不起作用

标签 c# asp.net unit-testing moq

我尝试使用 SetupSequence Moq 4.5框架的方法。

应该模拟的类:

public class OutputManager {
    public virtual string WriteMessage(string message) {
    // write a message
    }
}

模拟:

var outputManagerMock = new Mock<OutputManager>();
var writeMessageCalls = 0;
var currentMessage = String.Empty;

outputManagerMock.Setup(o => o.WriteMessage(It.IsAny<string>())).Callback((string m) => {
    writeMessageCalls++;
    message = m;
});

这段代码工作正常。但我想对 WriteMessage 的每次调用进行不同的设置。方法。嗯,我用SetupSequence而不是 Setup :

var outputManagerMock = new Mock<OutputManager>();
var writeMessageCalls = 0;
var firstMessage = String.Empty;
var secondMessage = String.Empty;

outputManagerMock.SetupSequence(o => o.WriteMessage(It.IsAny<string>()))
.Callback((string m) => {
    writeMessageCalls++;
    firstMessage = m;
}).Callback((string m) => {
    writeMessageCalls++;
    secondMessage = m;
});

然后我得到了错误:

Error CS0411 The type arguments for method
'SequenceExtensions.SetupSequence<TMock, TResult>(Mock<TMock>, Expression<Func<TMock, TResult>>)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.

我在这里找到了可能的解决方案 - SetupSequence in Moq .但它看起来像是一种解决方法。

最佳答案

SetupSequence 用于根据尝试使用正在设置的方法的次数来设置返回序列。基于您的代码的示例演示了我在说什么:

outputManagerMock.SetupSequence(o => o.WriteMessage(It.IsAny<string>()))
.Returns("Hello for the first attempt!")
.Returns("This is the second attempt to access me!")
.Throws(new Exception());

关于c# - Moq SetupSequence 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39719702/

相关文章:

c# - 如何从 ASP.NET MVC 项目引用 Web 服务?

javascript - 捆绑 .js 文件与 CDN

java - 以编程方式一次又一次地运行 TestNG 测试

python - python 单元测试中的信息性消息

java - Junit无法读取更新后的代码

c# - OAuth。推特。 StatusCode : 403. 需要 SSL。 C#

c# - 在 C# 中列出赋值的变量?

javascript - 从 C# webbrowser 控件捕获 HTTP Web 请求

asp.net - 如何更改 SQL Server 上的 ASP.Net Identity 2 以创建 newSequentialId 主键?

asp.net - 如何在数据绑定(bind)控件中使用 Eval 调用扩展方法