单元测试意外断言失败

时间:2018-03-17 00:15:07

标签: asp.net entity-framework unit-testing core razor-pages

我正在进行删除的单元测试:

[Fact]
 public async Task DeleteSupplierAsync_SupplierIsDeleted_WhenSupplierIsFound()
 {
     using (var db = new SulferFireDbContext(Utilities.TestingDbContextOptions()))
     {
         // Arrange
         var seedSuppliers = SulferFireDbContext.GetSeedingSuppliers();
         await db.AddRangeAsync(seedSuppliers);
         await db.SaveChangesAsync();
         var recId = 123;
         var expectedSuppliers = seedSuppliers.Where(supplier => supplier.ID != recId).ToList();
         // Act
         await db.DeleteSupplierAsync(recId);
         // Assert
         var actualSuppliers = await db.Suppliers.AsNoTracking().ToListAsync();
         Assert.Equal(expectedSuppliers, actualSuppliers);
     }
}

问题是expectedSuppliersactualSuppliers似乎是等于,但测试失败了。这在Assert.Equals调试后出现:

Exception

提前致谢!

1 个答案:

答案 0 :(得分:2)

Assert.Equal使用对象的.Equal来比较两个对象。由于List<>是一种参考类型,因此您的比较将失败。

使用CollectionAssert来比较两个集合。我建议AreEquivalent

//...code removed for brevity

CollectionAssert.AreEquivalent(expectedSuppliers, actualSuppliers);