Moq定义严格的模拟

时间:2014-02-07 20:12:11

标签: c# unit-testing moq

是否可以在Moq中定义严格的行为?

我想两次调用ReadLine,但为两个不同的调用定义不同的返回值。请参阅下面的代码示例:

Moq示例(失败)

[Test]
public void ExampleDifferentResultOnReadLine()
{
    var textReader = new Mock<TextReader>(MockBehavior.Strict);
    textReader.Setup(reader => reader.ReadLine()).Returns("Bla");
    textReader.Setup(reader => reader.ReadLine()).Returns("Bla1");

    var str = textReader.Object.ReadLine();
    var str1 = textReader.Object.ReadLine();

    Assert.AreEqual("Bla", str); // Fails: mocks returns Bla1
    Assert.AreEqual("Bla1", str1);
}

Rhino模拟示例(成功)

public void ExampleDifferentResultOnReadLine()
{
    var textReader = MockRepository.GenerateStrictMock<TextReader>();
    // var textReader = new Mock<TextReader>(MockBehavior.Strict);
    textReader.Expect(reader => reader.ReadLine()).Return("Bla");
    textReader.Expect(reader => reader.ReadLine()).Return("Bla1");

    var str = textReader.ReadLine();
    var str1 = textReader.ReadLine();

    Assert.AreEqual("Bla", str);
    Assert.AreEqual("Bla1", str1);
}

与Moq一样可能吗?

1 个答案:

答案 0 :(得分:6)

模拟构造函数接受MockBehavior枚举值:

var textReader = new Mock<TextReader>(MockBehavior.Strict);

BTW正确的代码来测试调用序列(因为RhinoMocks增加了期望值,而Moq只使用你提供的最后一个值):

var textReader = new Mock<TextReader>();
textReader.SetupSequence(r => r.ReadLine())
          .Returns("Bla")
          .Returns("Bla1");

var str = textReader.Object.ReadLine();
var str1 = textReader.Object.ReadLine();

Assert.AreEqual("Bla", str);
Assert.AreEqual("Bla1", str1);