Can mock objects setup to return two desired results?

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

Can mock objects be used to return more than one desired result like below?

mockObject.Setup(o => o.foo(It.IsAny<List<string>>())).Returns(fooBall); mockObject.Setup(o => o.foo(It.IsAny<int>())).Returns(fooSquare);

回答1:

Yes, you can use these setups. Thus arguments of foo method call are different (any integer and any list of strings), you have two different setups here, each with its own return value. If you would have same arguments, then last setup would replace previous setup(s).

Remember - each setup is defined by member you call and arguments you pass.



回答2:

In your example, because the two foo methods take different parameter types, they are overloads, and as Sergey states, these are regarded as entirely separate methods to both the compiler, and to Moq.

In the specific case where you want to return different results for the same method, depending on the values of the inputs, you can use It.Is<> with a predicate matcher to specify the filter to be applied to the parameters. Define these from most generic to most specific, e.g. focusing on just the o.foo(int) overload:

mockObject.Setup(o => o.foo(It.IsAny<int>())).Returns(defaultFoo); mockObject.Setup(o => o.foo(It.Is<int>(i => i == 5))).Returns(fooBall); mockObject.Setup(o => o.foo(It.Is<int>(i => i > 50 && i % 2 == 0)))    .Returns(fooSquare);


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