Home > database >  How to return two different values depending on the argument values in Moq method setup?
How to return two different values depending on the argument values in Moq method setup?

Time:04-20

I have a test where at some point two lists are compared.

IsEqual(List<string> a, List<string> b, ComparisonConfig conf)

The above function returns true result if List A equals List B and false result otherwise.

In tests I need to setup this function so it returns correct outcome when its called.

_service
    .Setup(x => x.IsEqual(It.IsAny<List<string>>(), It.IsAny<List<string>>(), null))
    .Returns(Result.Ok(true));

for now this always returns true even though lists are not equal.

So the question is how can I make this setup return Result.Ok(true) when arguments are equal and Result.Ok(false) otherwise.

CodePudding user response:

Returns has several overloads accepting Func's with different number of parameters so it is possible to access invocation arguments when returning a value:

_service.Setup(x => x.IsEqual(It.IsAny<List<string>>(), It.IsAny<List<string>>(), null))
    .Returns((List<string> l1, List<string> l2, ComparisonConfig c) => 
    {
        if(...) // some logic with l1 and l2
        {
            return Result.Ok(true);
        }
        return Result.Ok(false);
    });

The delegate used by Returns should match the signature and return type of the member being setup.

  • Related