【问题标题】:Skip type check in collection equality in xUnit在 xUnit 中跳过集合相等性中的类型检查
【发布时间】:2019-03-17 13:36:36
【问题描述】:

有一个微不足道的继承

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 接口,则集合重载也应该使用该接口并且不比较类型。如何获得想要的行为?

【问题讨论】:

  • 如果这条线索死了,我建议在 xunit github 上询问

标签: c# .net collections xunit xunit.net


【解决方案1】:

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

我想到了类似的东西

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

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

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

【讨论】:

    猜你喜欢
    • 2018-09-27
    • 2011-07-25
    • 2012-06-23
    • 2013-05-31
    • 1970-01-01
    • 2017-01-20
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多