最小起订量如果方法设置相交会怎样?

MOQ what happen if method setup intersect?

如果您愿意,当两个设置相交或重叠时会发生什么。

例如,在下面的场景中设置重叠,因为显然 "aSpecificString" 也被视为任何字符串。

Interface ISomeInterface
{
    int SomeMethod(string param);
}

[TestMethod]
public void SomeClass_ShouldBehaveProperly_GivenSomeScenario()
{
    var mock = new Mock<ISomeInterface>(MockBehavior.Strict);
    mock.Setup(m => m.SomeMethod("aSpecificString"))
        .Returns(100);
    mock.Setup(m => m.SomeMethod(It.IsAny<string>()))
        .Returns(0);

    /*the rest of the test*/
}

我想知道当它相交时会发生什么。

它会抛出异常还是无法检测到重叠并按添加顺序使用第一个匹配设置?

我认为最好避免重叠设置。

根据在线找到的文档,最后一次调用获胜并使之前的调用无效。

所以即使在你的情况下,如果测试是调用

SomeMethod("aSpecificString")

它将 return 0 基于您示例中的设置。

不要走你正在走的路。我只看到大量的痛苦。相反,让你的 Return 有条件:

mock.Setup(m => m.SomeMethod(It.IsAny<string>()))
    .Returns((string parameter) => parameter == "aSpecificString" ? 100 : 0);

希望在您开始编写重要代码之前我能联系到您...