首页 > 解决方案 > 在 xUnit 中跳过集合相等性中的类型检查

问题描述

有一个微不足道的继承

private class TestBase : IEquatable<TestBase> {
    public string Name { get; set; } = "test1";

    public bool Equals(TestBase other) => this.Name == other.Name;
}

private class Test : TestBase {}

我需要比较两个集合:

var s1 = new TestBase();
var s2 = new Test();
Assert.Equal(s1, s2); // OK, uses IEquatable
Assert.StrictEqual(s1, s2); // OK uses IEquatable
Assert.Equal(new[] { s1 }, new[] { s2 }); // fails
Assert.Equal<IEnumerable<TestBase>>(new[] { s1 }, new[] { s2 }); // fails
Assert.Equal(new TestBase[] { s1 }, new TestBase[] { s2 }); // fails

对我来说,如果Assert.Equal()单个实例使用IEquatable接口,则集合重载也应该使用接口并且不比较类型。我如何获得想要的行为?

标签: c#.netcollectionsxunitxunit.net

解决方案


您是否尝试过使用 Fluent Assertions 进行此比较?

我想到了类似的东西

x = new[] {s1};
y = new[] {s2};
x.Should().BeEquivalentTo(y, o => o.Excluding(p => p.Type));

它比较了两个对象集合彼此等价但忽略了类型。我还没有尝试使用类型的 Excluding() 部分,但它适用于单个对象属性,所以也许尝试让它也适用于您的示例。

有关 Fluent 断言的更多信息:https ://fluentassertions.com/about/


推荐阅读