Moq:使用MockBehavior.Strict设置模拟的异常

时间:2014-03-26 13:46:21

标签: moq

Moq库中是否有一种机制可以将特定方法设置为Loose,以便VerifyAll不会因该方法而失败。

[TestFixture]
public class MockStrictException
{
    [Test]
    public void exception_to_setup_strict()
    {
        var mock = new Mock<ITest>(MockBehavior.Strict);
        SetupAsPartOfTestSuite(mock);

        ITest subject = mock.Object;
        //Act
        subject.Called().Should().Be(10);

        mock.VerifyAll();
    }

    //Contrived example, however is actual usage there are setup helper methods
    //I understand it should not have been setup as strict 
    //but way too much effort to fix all test cases
    private static void SetupAsPartOfTestSuite(Mock<ITest> mock)
    {
        mock.Setup(x => x.Called()).Returns(10);
        //TODO: Is there a way to override this setup
        mock.Setup(x => x.NotCalled()).Returns(-10);
    }

    public interface ITest
    {
        int Called();
        int NotCalled();
    }
}

1 个答案:

答案 0 :(得分:0)

2件事:

 mock.Setup(x => x.Called()).Returns(10);
    //TODO: Is there a way to override this setup
    mock.Setup(x => x.NotCalled()).Returns(-10);

如果您通过将其更改为:

来使其可验证,这将是有意义的
 mock.Setup(x => x.Called()).Returns(10).Verifiable();
 mock.Setup(x => x.NotCalled()).Returns(-10).Verifiable();

你为什么要称之为严格的行为?或者创建一个单独的测试方法并单独验证它们?另外,我建议您简要介绍一下This Link Here,以便更好地了解Moq的验证。

你的问题的直接答案是没有 Moq库不包含创建松散类的预定义方法,但我确定你是否想要创建自己的辅助扩展.B < / p>