148
votes

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?

3

3 Answers

250
votes

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.

20
votes

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

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

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);