c# - 如何等待以特定 linq 表达式作为参数的调用

标签 c# linq unit-testing expression fakeiteasy

我有一个电话想要查看是否已发生。此调用是对采用 Linq 表达式作为参数的方法。此表达式根据声明该表达式的局部变量的 id 来测试对象 id。我如何才能轻松调用该触发器,仅当 Linq 表达式相等(用局部变量替换)时才触发,或者如果在 linq 表达式中使用的局部变量等于某个值时不可能触发该触发。

我当前的代码如下所示

   A.CallTo(() => SomeMethod.FindBy(item=> item.ItemId == 3)).MustHaveHappened(Repeated.Exactly.Once);

作为正在测试的代码中对 and this 的调用。

SomeMethod.FindBy(item=> item.ItemId == id)

其中 id 是局部变量。这不起作用,因为在进行调用时 id 未被替换,并且我收到这样的错误。

SomeInterface`1[[someItem, someItemFolder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].FindBy(item=> (item.ItemId == 3))
  Expected to find it exactly once but found it #0 times among the calls:
    1: SomeInterface`1[UKHO.WeeklyRecipes.EFModels.EFModels.EfTag].FindBy(predicate: tag => (tag.TagId == value(UKHO.WeeklyRecipes.BusinessLayer.PreferenceQueries+<>c__DisplayClass2_0).id))

最佳答案

您看到此行为是因为 FakeItEasy 无法判断两个表达式是否相同。当您提供一个对象作为参数约束时,FakeItEasy 会尝试 match the argument value exactly 。在本例中,这意味着调用 ExpressionEquals 方法。引用文档:

When checking for argument equality, FakeItEasy uses object.Equals. If the type to be checked does not provide an adequate Equals method, you may have to use the That.Matches method described in Custom matching. Be particularly careful of types whose Equals methods perform reference equality rather than value equality. In that case, the objects have to be the same object in order to match, and this sometimes produces unexpected results. When in doubt, verify the type's Equals behavior manually.

因此,本质上这意味着如果您创建了两个变量,一个包含表达式 item => item.ItemId == 3 ,另一个包含 item.ItemId == id > 并使用 Equals 比较它们,您会看到 false 结果,FakeItEasy 也是如此。

一种方法是捕获表达式,然后询问它以查看它是否按照您的意愿运行(即接受 3 并拒绝非 3)。这很尴尬,但是比较谓词很困难。我在 How to test for a Match with FakeItEasy on a predicate call? 的回答中详细讨论了这一点。 .

关于c# - 如何等待以特定 linq 表达式作为参数的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45103147/

相关文章:

c# - 如何使用类本身作为方法参数?

c# - 选择整个第一个表,并用连接表覆盖一列

c# - 使用linq删除gridview中的行

c# - EF AsNoTracking 导致错误。类型 'System.DateTime' 的表达式不能用于分配类型 'System.Nullable` 1[System.DateTime]'

c# - EF6 : Use reference/lookup data with IQueryable

c# - 在单元测试中模拟 IHttpContextAccessor

c# - Linq to EF .Clear() 不清除

php - 单元测试oAuth2授权码

unit-testing - 在 Grails 中,如何在自动化测试中测试 @Secured 注释?

java - JUnit 5 中的 TestName 规则等效于什么?