gpt4 book ai didi

c# - CollectionAssert.AreEquivalent 失败......无法弄清楚为什么

转载 作者:行者123 更新时间:2023-11-30 19:28:23 24 4
gpt4 key购买 nike

我有一个正在单元测试的注入(inject)接口(interface)。有问题的方法是有效的,但我正在尝试编写一个单元测试来确认返回的样本数据是完整和准确的。我的测试看起来正确,甚至结果看起来相同,但测试失败并显示“CollectionAssert.AreEquivalent 失败。预期集合包含 1 次出现。实际集合包含 0 次出现。”

[TestMethod]
public void Should_Get_All_Amenities()
{
var amenitiesRep = _ninjectKernel.Get<IAmenityRepository>();

var amenities = amenitiesRep.GetAmenities();

var expected = new List<Amenity>
{
new Amenity() {Id = 1, Name = "Pool", Category = "resort"},
new Amenity() {Id = 2, Name = "Hottub", Category = "resort"},
new Amenity() {Id = 3, Name = "Steamroom", Category = "unit"}
};

Assert.IsNotNull(amenities);
Assert.IsTrue(amenities.Count() == 3);
CollectionAssert.AreEquivalent(expected, amenities);
}

(相关代码来 self 的TestRepository)

        var amenities = new List<Amenity>
{
new Amenity() {Id = 1, Name = "Pool", Category = "resort"},
new Amenity() {Id = 2, Name = "Hottub", Category = "resort"},
new Amenity() {Id = 3, Name = "Steamroom", Category = "unit"}
};

var mockAmenitiesRep = new Mock<IAmenityRepository>();
mockAmenitiesRep.Setup(_m => _m.GetAmenities()).Returns(amenities);
Kernel.Bind<IAmenityRepository>().ToConstant(mockAmenitiesRep.Object);

我可以确认 CollectionAssert 中的所有数据都已正确填充,每个字段看起来都是 1 对 1 匹配,相同数量的对象,相同的对象类型,所以我只是不知道测试失败的原因。

(编辑:代码失败的行是 CollectionAssert)

最佳答案

这是因为 Amenity 是引用类型,所以 CollectionAssert.AreEquivalent 通过引用的地址检查相等性。由于预期集合中的项目与您从 GetAmenities() 方法获得的对象不同,因此它返回 false。您必须覆盖 Amenity 类中的相等比较器。

public override bool Equals(object obj)
{
var other = obj as Amenity;
if(other == null)
{
return false;
}

return Id = other.Id && Name == other.Name && Category == other.Category;
}

public override int GetHashCode()
{
return Id.GetHashCode(); //assumes Id is immutable
}

更新:

请记住,这种方法不是很好,因为它会导致 Equality Pollution . Alexander Stepaniuk 在评论中发布了一个更好的选择。

关于c# - CollectionAssert.AreEquivalent 失败......无法弄清楚为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821628/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com