通过使用 Fluent Assertions 在嵌套列表中包含属性来测试列表等效性
Testing list equivalency by including properties in nested lists using Fluent Assertions
有没有办法通过位于嵌套列表中的属性断言两个对象列表的等价性?我知道您只能使用 ShouldAllBeEquivalentTo() 和 Include() 测试某些属性的等效性,但我想在嵌套列表中定义的 属性 上调用 Include():
class A
{
public B[] List { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
class B
{
public string PropertyToInclude { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
var list1 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
var list2 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
list1.ShouldAllBeEquivalentTo(list2, options => options
.Including(o => o.List.Select(l => l.PropertyToInclude))); // doesn't work
目前还没有一种惯用的方法来实现这一点,但 API 足够灵活,尽管是以一种更加笨拙的方式。
关于这个问题有一个open issue,里面也列出了一些解决方法。
对于当前的 API(版本 5.7.0),您发布的示例可以通过仅包含 属性 List
,然后排除以 [=12 结尾的属性来断言=].
var list1 = new[]
{
new A
{
SomePropertyIDontCareAbout = "FOO",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BAZ"
},
}
},
};
var list2 = new[]
{
new A
{
SomePropertyIDontCareAbout = "BOOM",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BOOM"
},
}
},
};
// Assert
list1.Should().BeEquivalentTo(list2, opt => opt
.Including(e => e.List)
.Excluding(e => e.SelectedMemberPath.EndsWith(nameof(B.SomePropertyIDontCareAbout))));
有没有办法通过位于嵌套列表中的属性断言两个对象列表的等价性?我知道您只能使用 ShouldAllBeEquivalentTo() 和 Include() 测试某些属性的等效性,但我想在嵌套列表中定义的 属性 上调用 Include():
class A
{
public B[] List { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
class B
{
public string PropertyToInclude { get; set; }
public string SomePropertyIDontCareAbout { get; set; }
}
var list1 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
var list2 = new[]
{
new A
{
List = new[] {new B(), new B()}
},
};
list1.ShouldAllBeEquivalentTo(list2, options => options
.Including(o => o.List.Select(l => l.PropertyToInclude))); // doesn't work
目前还没有一种惯用的方法来实现这一点,但 API 足够灵活,尽管是以一种更加笨拙的方式。
关于这个问题有一个open issue,里面也列出了一些解决方法。
对于当前的 API(版本 5.7.0),您发布的示例可以通过仅包含 属性 List
,然后排除以 [=12 结尾的属性来断言=].
var list1 = new[]
{
new A
{
SomePropertyIDontCareAbout = "FOO",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BAZ"
},
}
},
};
var list2 = new[]
{
new A
{
SomePropertyIDontCareAbout = "BOOM",
List = new[]
{
new B()
{
PropertyToInclude = "BAR",
SomePropertyIDontCareAbout = "BOOM"
},
}
},
};
// Assert
list1.Should().BeEquivalentTo(list2, opt => opt
.Including(e => e.List)
.Excluding(e => e.SelectedMemberPath.EndsWith(nameof(B.SomePropertyIDontCareAbout))));