没有指定输入参数的Moq模拟方法

Ano*_*use 125 c# moq mocking

我在使用Moq的测试中有一些代码:

public class Invoice
{
    ...

    public bool IsInFinancialYear(FinancialYearLookup financialYearLookup)
    {
        return InvoiceDate >= financialYearLookup.StartDate && InvoiceDate <= financialYearLookup.EndDate;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

所以在单元测试中我试图模拟这个方法并让它返回true

mockInvoice.Setup(x => x.IsInFinancialYear()).Returns(true);
Run Code Online (Sandbox Code Playgroud)

无论如何都要写这行,所以我不必指定输入IsInFinancialYear.即.所以它在代码中没有输入参数是什么,它将返回true传递给它的什么?

Jef*_*ata 209

您可以使用It.IsAny<T>()匹配任何值:

mockInvoice.Setup(x => x.IsInFinancialYear(It.IsAny<FinancialYearLookup>())).Returns(true);
Run Code Online (Sandbox Code Playgroud)

请参阅快速入门的" 匹配参数"部分.

  • 同意这里的其他评论:为任何非平凡的方法输入这个是一个主要的痛苦。 (6认同)
  • @Brandon然后你有一个It.IsAny <type>()用于每个参数,其中type是param所属的类型.如果你想要,你可以写一个帮助函数,通过反射为你做这个. (5认同)
  • 我意识到这个答案很老但是如果我有一个以上的简单参数怎么办?是否可以只说"任何类型适合所有参数"? (4认同)

jeh*_*eha 16

尝试使用It.IsAny<FinancialYearLookup>()接受任何参数:

mockInvoice.Setup(x => x.IsInFinancialYear(It.IsAny<FinancialYearLookup>())).Returns(true);
Run Code Online (Sandbox Code Playgroud)


小智 6

您可以尝试以下方法:

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

允许:

mock
.SetupIgnoreArgs(x => x.Method(null, null, null)
.Return(value);
Run Code Online (Sandbox Code Playgroud)

  • 拉请求到Moq扩展将不胜感激:-) (2认同)