c# - FakeItEasy ReturnLazily 具有超过 4 个参数的方法

标签 c# unit-testing fakeiteasy

使用 FakeItEasy,我想伪造一个接口(interface)方法来返回一些自定义列表,该方法有超过 4 个参数,方法的签名是这样的:

     IList<Employee> FindAll(DateTime dateFrom, DateTime dateTill, Guid locationId, Gender gender, int age);

虽然 FakeItEasy 有 ReturnsLazily 方法,它只支持 4 个参数,所以对于这个 5 个参数的方法,我不能使用 ReturnsLazily 功能。

    A.CallTo(() => repAssign.FindAll(A<DateTime>.Ignored,A<DateTime>.Ignored,A<Guid>.Ignored,A<Gender>.Ignored,A<Int>.Ignored))
         .ReturnsLazily((DateTime StartDate, DateTime EndDate, Guid locationId, Gender gender, int age) =>
         return list.Where(...some filters here as per arguments...).ToList();
        );

对于 FakeItEasy,请建议如何对具有 4 个以上参数的方法使用 ReturnsLazily。

最佳答案

您需要使用将 IFakeObjectCall 作为 lambda 参数的重载并从 there 中提取参数:

If more advanced decision-making is required, or the method has more than 4 parameters, the convenience methods won't work. Use the variant that takes an IFakeObjectCall instead

 A.CallTo(() => repAssign.FindAll(
     A<DateTime>.Ignored,
     A<DateTime>.Ignored,
     A<Guid>.Ignored,
     A<Gender>.Ignored,
     A<Int>.Ignored))
.ReturnsLazily(call => 
    list
        .Where(x => call.GetArgument<Int>(4) > 1)
        .ToList()
);

可以通过 GetArgument 泛型方法提取参数,该方法将参数类型作为泛型参数和参数位置(从 0 开始)。

附带说明一下,您应该考虑重构此类方法。这么多参数最好包装成 parameter object class :

var filterParameters = new FilterParameters
{
    LocationGuid = guid,
    Gender = Gender.Female,
};
var result = repo.FindAll(filterParameters);

这将使引入新参数变得更加容易,并有助于避免此类问题。

关于c# - FakeItEasy ReturnLazily 具有超过 4 个参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31018199/

相关文章:

c# - 从 C# 错误打开 Office 2010 文档

c# - 检测到具有不兼容类型的二元运算符。发现操作数类型 edm.string 和 edm.guid 的种类相等

c# - 强制linq执行内连接

java - 由另一个类扩展的类的模拟方法

c# - FakeItEasy 为后续调用模拟方法返回不同的值

c# - 在 Excel 图表 c# 中旋转 X 轴

angularjs - 如何模拟单元测试的配置阶段提供程序?

php - 单元测试构造函数的最佳方法是什么?

c# - 如何使用 FakeItEasy 伪造 Action <>

c# - FakeItEasy:在不指定类型的情况下伪造对泛型方法的调用