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);
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With