c# - 为什么在使用 "Including"时 FluentAssertions 中会忽略嵌套类?

标签 c# .net fluent-assertions

为了说明这个问题,考虑这三个类:

class Orange
{
    public String color { get; set; }
}
class Foo
{
    public Int32 size { get; set; }
    public Orange orange { get; set; }
}
class Bar
{
    public Int32 size { get; set; }
    public Orange orange { get; set; }
}

如果我创建 Foo 和 Bar 的实例,并将它们的 Orange 实例设置为不同的实例,然后进行断言(不使用“Including”),那么断言会按预期工作;它找出“red”和“bff”之间的区别:

Foo foo = new Foo() { size = 3 };
foo.orange = new Orange() {color = "red" }; 

Bar bar = new Bar() { size = 3 };
bar.orange = new Orange() { color = "bff" };

foo.ShouldBeEquivalentTo(bar);  // assertion fails, as expected

但是如果我做同样的断言,同时通过“包括”明确告诉 FluentAssertions 要比较的内容,断言不会捕捉到 Orange 中的差异:

foo.ShouldBeEquivalentTo(bar, options => options
    .Including(o => o.size)
    .Including(o => o.orange)
    );   // assertion does not fail, why?

最佳答案

您可以使用 ComparingByValue

foo.ShouldBeEquivalentTo(bar, options => options
    .Including(o => o.size)
    .Including(o => o.orange)
    .ComparingByValue<Orange>());

然后它失败了。

您已包含 orange用于比较和比较对象的属性基于它们的属性,您不包括 orange 的任何属性所以要比较foo.orange假定等于 bar.orange .

添加CompareByValue<Orange>进行比较Orange基于他们的实例 Equals方法。所以默认情况下它会进行引用比较。

你应该覆盖 Equals对于 Orange

class Orange
{
    public String color { get; set; }

    public override bool Equals(object obj)
    {
        var orange = obj as Orange;
        return Equals(orange);
    }

    protected bool Equals(Orange other)
    {
        return other != null && 
            string.Equals(color, other.color);
    }

    public override int GetHashCode()
    {
        return color?.GetHashCode() ?? 0;
    }
}

现在您甚至可以使用这种方法比较列表。

var foo = new Foo() { size = 3 };
var o1 = new Orange { color = "a" };
var o2 = new Orange { color = "a" };
var o3 = new Orange { color = "b" };
var o4 = new Orange { color = "b" };
foo.orange = new List<Orange>() { o1, o3 };

Bar bar = new Bar() { size = 3 };
bar.orange = new List<Orange>() { o1, o4 };

foo.ShouldBeEquivalentTo(bar);

foo.ShouldBeEquivalentTo(bar, options => options
    .Including(x => x.size)
    .Including(x => x.orange)
    .ComparingByValue<Orange>());

关于c# - 为什么在使用 "Including"时 FluentAssertions 中会忽略嵌套类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993239/

相关文章:

.net - 希望创建客户端应用程序 (WPF) 来对远程数据执行 CRUD 操作

c# - Fluent-ASsertions ShouldRaisePropertyChangeFor 不适用于异步任务?

c# - 比较某些 Prop 具有不同格式的对象

c# - 允许 CON,URL 中的保留关键字

c# - 将应用程序池凭据用于 WebClient 请求

c# - 将 Javascript 数组转换为 C# 列表

c# - 为什么 nameof() 在 Linq 表达式中给出了不明确的调用警告,但当我使用与字符串相同的值时却没有?

c# - 将现有 Azure 帐户与 Azure AD 集成

.net - 更新 .NET Core 托管 bundle 需要重新启动 IIS?

.net - 我可以在不注释类的情况下自定义Json.NET序列化吗?