167

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?

jeha
  • 10,562
  • 5
  • 50
  • 69
AnonyMouse
  • 18,108
  • 26
  • 79
  • 131

3 Answers3

278

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.

tronda
  • 3,902
  • 4
  • 33
  • 55
Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
  • 9
    I realize this answer is old but what if I have more than one simple parameter? Is it possible to just say "Anything where the types fit for all parameters"? – Brandon Mar 02 '16 at 19:13
  • 7
    @Brandon Then you have an It.IsAny() for each parameter where type is whatever type that param is. If you wanted you could probably write a helper function that does this for you via reflection. – user441521 Sep 08 '16 at 20:05
  • 1
    https://7pass.wordpress.com/2014/05/20/moq-setup-and-ignore-all-arguments/ – NDC Jun 30 '17 at 17:44
  • 7
    Agree with the other comments here: typing this for any non-trivial method is a major pain. – John Hargrove Jan 11 '18 at 22:49
  • Any one does have any helper that do this ? Or you have to write for each single method a helper / – Meysam Sep 04 '18 at 14:39
20

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

mockInvoice.Setup(x => x.IsInFinancialYear(It.IsAny<FinancialYearLookup>())).Returns(true);
jeha
  • 10,562
  • 5
  • 50
  • 69
14

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);
NDC
  • 531
  • 4
  • 11