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?
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.
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