【发布时间】:2017-01-16 12:45:22
【问题描述】:
我正在使用 FluentAssertions,我需要比较 2 个对象列表。它们来自包含 Values 属性的同一类。
我想比较两个列表,但我希望 list1 中的所有值都存在于 list2 中,但忽略额外的值。像这样的:
using System.Collections.Generic;
using FluentAssertions;
public class Program
{
public class Value
{
public int Id { get; set; }
public string SomeValue { get; set; }
}
public class MyClass
{
public int Id { get; set; }
public string Name { get; set; }
public List<Value> Values { get; set; }
}
public static void Main()
{
var list1 = new List<MyClass>
{
new MyClass
{
Id = 1,
Name = "Name 1",
Values = new List<Value>
{
new Value {Id = 1, SomeValue = "Test" }
}
}
};
var list2 = new List<MyClass>
{
new MyClass
{
Id = 1,
Name = "Name 1",
Values = new List<Value>
{
new Value {Id = 1, SomeValue = "Test" },
new Value {Id = 2, SomeValue = "Test" }
}
}
};
list2.Should().HaveSameCount(list1);
// This doesn't throw, just proving that the first object is equivalent
list2[0].Values[0].ShouldBeEquivalentTo(list1[0].Values[0]);
for (var x = 0; x < list2.Count; x++)
{
list2[x].ShouldBeEquivalentTo(list1[x], options => options.Excluding(s => s.Values));
// This throws, but it shouldn't
list2[x].Values.Should().Contain(list1[x].Values);
}
}
}
但这会引发:
预期收集{
Program+Value { Id = 1 SomeValue = "Test" },
Program+Value { Id = 2 SomeValue = "Test" }} 包含
程序+值 { Id = 1 SomeValue = "测试" }
所以有几个问题:
为什么 Contains 没有按预期工作?
是否可以在一行中做到这一点,例如将默认列表比较更改为使用 Contains 而不是 ShouldBeEquivalentTo?
如何从类的集合中排除属性? 我看过this question 和this one,但它们似乎不适用于集合。此外,如果我尝试使用 PropertyPath,程序也不会编译。我正在使用 .Net Core,但我也尝试使用 4.6,但它也不起作用。
【问题讨论】:
标签: c# fluent-assertions