Moq mock method with out specifying input parameter

C#MockingMoq

C# Problem Overview


I have some code in a test using Moq:

public class Invoice
{
    ...

    public bool IsInFinancialYear(FinancialYearLookup financialYearLookup)
    {
        return InvoiceDate >= financialYearLookup.StartDate && InvoiceDate <= financialYearLookup.EndDate;
    }
    ...
}

So in a unit test I'm trying to mock this method and make it return true

mockInvoice.Setup(x => x.IsInFinancialYear()).Returns(true);

Is there anyway to write this line so I don't have to specify the input to IsInFinancialYear. ie. So that it doesn't in the code what the input parameter is it will return true whatever is passed to it?

C# Solutions


Solution 1 - C#

You can use It.IsAny<T>() to match any value:

mockInvoice.Setup(x => x.IsInFinancialYear(It.IsAny<FinancialYearLookup>())).Returns(true);

See the Matching Arguments section of the quick start.

Solution 2 - C#

Try using It.IsAny<FinancialYearLookup>() to accept any argument:

mockInvoice.Setup(x => x.IsInFinancialYear(It.IsAny<FinancialYearLookup>())).Returns(true);

Solution 3 - C#

You can try the following:

https://7pass.wordpress.com/2014/05/20/moq-setup-and-ignore-all-arguments/

Allows:

mock
.SetupIgnoreArgs(x => x.Method(null, null, null)
.Return(value);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnonyMouseView Question on Stackoverflow
Solution 1 - C#Jeff OgataView Answer on Stackoverflow
Solution 2 - C#jehaView Answer on Stackoverflow
Solution 3 - C#NDCView Answer on Stackoverflow