Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock method return based on object parameter

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?

like image 802
Alex Avatar asked Jan 28 '23 09:01

Alex


1 Answers

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.

like image 102
Matt Dillard Avatar answered Feb 06 '23 14:02

Matt Dillard