Reputation: 3998
I have the following (simplified) code:
public string methodName(ClassType object)
{
If(object.value == 1)
return "Yes";
else If(object.value == 2)
return "No";
else
return "whatever";
}
I am then calling this method in a unit test, and need to mock the return type based on the object value:
_Service.Setup(x => x.methodName(new methodName { value = 1}).Returns("Yes");
_Service.Setup(x => x.methodName(new methodName { value = 2}).Returns("No");
I know what I have written is wrong - but how can I achieve this?
Upvotes: 4
Views: 6246
Reputation: 14863
You're on the right track. With Moq, you need to specify exactly which setup should match each input. You do it like this:
_Service.Setup(x => x.methodName(It.IsAny<ClassType>())).Returns("whatever");
_Service.Setup(x => x.methodName(It.Is<ClassType>(o => o.value == 1))).Returns("Yes");
_Service.Setup(x => x.methodName(It.Is<ClassType>(o => o.value == 2))).Returns("No");
The first line there sets up the mock to return "whatever" whenever this method is called with any value. The following two lines override that behavior for specific values.
I'd check out Moq's Quickstart guide for more details, and the Matching Arguments section in particular.
Upvotes: 5
Reputation: 37113
I´m not that familiar with Moq, however I asume the following should do it. You should provide a single Returns
for every possible value for your parameter:
_Service.Setup(x => x.methodName(It.Is<ClassType>(y => y.value == 1))).Returns("Yes");
_Service.Setup(x => x.methodName(It.Is<ClassType>(y => y.value == 2))).Returns("No");
This way whenever your methodName
-method is called with object.value == 1
, "Yes"
is returned, while object.value == 2
resolves to the method returning "No"
.
However to me this makes not much sense as you´re mocking the behaviour of methodName
with the exact same behaviour. I suppose this is just for research.
Upvotes: 3