Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can mock objects setup to return two desired results?

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);
like image 654
Pramuka Avatar asked Jun 12 '14 18:06

Pramuka


2 Answers

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.

like image 176
Sergey Berezovskiy Avatar answered Oct 03 '22 11:10

Sergey Berezovskiy


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);
like image 41
StuartLC Avatar answered Oct 03 '22 12:10

StuartLC