使用Moq模拟方法而不指定输入参数

169

我在使用Moq编写测试的一些代码:

public class Invoice
{
    ...

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

所以在一个单元测试中,我试图模拟这个方法并使其返回true。

mockInvoice.Setup(x => x.IsInFinancialYear()).Returns(true);
有没有办法编写这行代码,以便我不必指定输入到 IsInFinancialYear。也就是说,无论传递给它什么参数,它都将返回 true,而不会在代码中指定输入参数?
3个回答

282

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

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

请参见快速入门中的匹配参数部分。


9
我知道这个回答有点旧了,但是如果我有多个简单参数怎么办?是否可以只说“任何类型都适合所有参数”的内容? - Brandon
7
针对每个参数,您都需要一个It.IsAny<type>(),其中"type"为该参数的类型。如果需要的话,您可以通过反射编写一个帮助函数来代替手动操作。 - user441521
1
https://7pass.wordpress.com/2014/05/20/moq-setup-and-ignore-all-arguments/ - NDC
7
同意其他评论:对于任何非平凡的方法,输入这些内容都是非常痛苦的。 - John Hargrove
有没有任何辅助工具可以做到这一点?或者你必须为每个单独的方法编写一个辅助工具。 - Meysam

20

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

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

14

8
欢迎提供给 Moq 扩展的 Pull Request :-) - Maurice Klimek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接