c# - 工作 LINQ 查询在单元测试中不起作用

标签 c# linq unit-testing moq

我有一个与此非常相似的查询:

var result = context.EntityRole
   .Where(er => er.EntityType.EntityTypeId == entityTypeIdParameter
                && er.Entity.SomeItems.Any(item => item.ItemId == itemIdParameter))
   .ToList()
   .Distinct(customItemComparer)
   .OrderBy(er => er.Id)
   .ThenByDescending(er => er.IsApproved)
   .ToList();

customItemComparer 与此类似:

public class CustomItemComparer : IEqualityComparer<EntityRole>
{
   public bool Equals(EntityRole x, EntityRole y)
   {
      if (ReferenceEquals(x, y)) return true;

      if (ReferenceEquals(x, null) || ReferenceEquals(y, null)) return false;

      return x.Property1 == y.Property1
             && x.Property2 == y.Property2
             && x.Property3 == y.Property3;
   }

   public int GetHashCode(EntityRole obj)
   {
      if (ReferenceEquals(obj, null)) return 0;

      var hasProperty1 = obj.Property1.GetHashCode();
      var hasProperty2 = obj.Property2.GetHashCode();
      var hasProperty3 = obj.Property3.GetHashCode();

      return hasProperyt1 ^ hasProperty2 ^ hasProperty3;
   }
}

我遇到的问题是,当我运行应用程序时,我得到了预期的结果,显然所有不同的场景都完美无缺地工作,但是当我尝试对其进行单元测试时,查询总是返回一个对象,即使列表包含多个对象一个属性 1、2 和 3 不同的对象。

我的单元测试看起来像这样,我们使用最小起订量,为简洁起见删除了其他属性:

var roles = new List<EntityRole>
{
   new EntityRole
   {
      Property1 = true,
      Property2 = 5,
      Property3 = "something"
   },
   new EntityRole
   {
      Property1 = true,
      Property2 = 9,
      Property3 = "something"
   },
   new EntityRole
   {
      Property1 = false,
      Property2 = 5,
      Property3 = "something"
   },
   new EntityRole
   {
      Property1 = true,
      Property2 = 5,
      Property3 = "something else"
   }
}

contextMock.Setup(c => c.EntityRole).Returns(roles.AsQueryable);

var sut = new SubjectUnderTest();
sut.MethodWhereQueryIsExecuted();

//some code to verify results

所以就像我说的,即使列表中没有两个相同的对象,查询总是返回第一个。

此外,如果我在 CustomItemComparer 中放置断点,则在运行应用程序时执行会停止,但在调试测试时它不会停止。

所以确切的问题是,为什么 Distinct 在应用程序运行时运行良好,而在单元测试运行时却不起作用?

最佳答案

我在将 MOQ 与 Distinct 一起使用时遇到了同样的问题,它在生产中运行良好,但在测试中却惨遭失败。对于类型为 Mock<>.Object 的对象,似乎 distinct 不能按预期工作。

在我的场景中,我选择使用 MoreLINQ 的 DistinctBy 扩展。如果您只想使用 Linq,则可以使用 GroupBy 并取而代之的是每个组中的第一个。

关于c# - 工作 LINQ 查询在单元测试中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28197523/

相关文章:

c# - 在 instagram 中获取用户 ID

c# - 从 .NET 使用 Apple 的 Bonjour 服务?

c# - 从 .ashx 压缩 Javascript 在浏览器中返回解码错误

c# - 映射到现有的数据库表

python - 使用 unittest 和 argparse 测试参数解析

php - 如何创建一个 Doctrine 实体的模拟对象?

java - 单元测试离散傅里叶变换

linq - 使用linq对可观察的集合进行排序

linq - 如何使用 LINQ 对数据进行分层分组?

c# - 如何创建子对象的 Expression.Property