MOQ what happen if method setup intersect?

随声附和 提交于 2020-03-03 07:47:11

问题


What happen when two setup intersect or overlap if you prefer.

For example, in the below scenario the setup overlap because obviously "aSpecificString" is also considered as any string.

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*/
}

I wonder what happen when it intersect.

Does it throw an exception or does it fail to detect the overlap and use the first matching setup in the order they were added?

I think it's best to avoid overlapping setup.


回答1:


According to documentation found online, The last call wins and nullifies previous calls.

So even in your case if the test was to call

SomeMethod("aSpecificString")

it would return 0 based on the setup in your example.




回答2:


Don't go down the path that you are going. I only see reams and reams of pain. Instead, make your Return conditional:

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

I hope I managed to reach you before you started putting down significant code...



来源:https://stackoverflow.com/questions/39276400/moq-what-happen-if-method-setup-intersect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!