2

我有一个注入接口,我正在单元测试。有问题的方法有效,但我正在尝试编写一个单元测试来确认返回的样本数据是完整且准确的。我的测试对我来说看起来是正确的,甚至结果看起来都是一样的,但测试失败并显示“CollectionAssert.AreEquivalent failed。预期的集合包含 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);
    }

(来自我的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)

4

1 回答 1

9

这是因为 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
}

更新:

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

于 2013-04-04T21:11:25.437 回答