C# 深入比较嵌套集合与 FluentAssertions

问题描述 投票:0回答:1

如何编写单元测试,使以下两个对象被视为相等?通常,我如何确保通过匹配的索引位置(列表)和匹配的键(字典)将任意深度嵌套的集合与对应集合进行比较?我尝试使用 Fluent Assertions 库执行以下操作,但收到以下错误。

List<Dictionary<List<string>, string>> list1 = new(){
  new (){{new (){"a"}, "aaa"}, {new (){"z"}, "zzz"}},
  new (){{new (){"b"}, "bbb"}},
  new (){{new (){"c"}, "ccc"}}
};
List<Dictionary<List<string>, string>> list2 = new(){
  new (){{new (){"a"}, "aaa"}, {new (){"z"}, "zzz"}},
  new (){{new (){"b"}, "bbb"}},
  new (){{new (){"c"}, "ccc"}}
};

list1.Should().BeEquivalentTo(list2);
Unhandled exception. FluentAssertions.Execution.AssertionFailedException: Expected list1[0] to be a dictionary with 2 item(s), but it misses key(s) {{"a"}, {"z"}} and has additional key(s) {{"b"}}
Expected list1[1] to contain key {"b"}.
Expected list1[2] to contain key {"c"}.

With configuration:
- Use declared types and members
- Compare enums by value
- Compare tuples by their properties
- Compare anonymous types by their properties
- Compare records by their members
- Include non-browsable members
- Include all non-private properties
- Include all non-private fields
- Match member by name (or throw)
- Be strict about the order of items in byte arrays
- Without automatic conversion.
c# testing nunit fluent-assertions
1个回答
0
投票

我最初的问题是从 FluentAssertions 中开箱即用,因为存储在 Dictionary 中的键是对列表的引用,所以如果没有非常专业的逻辑就很难推断应该发生什么。请注意,以下是允许的,如果没有更多信息,则不清楚如何为所有重复的 List = {"a"} 键设计匹配器:

List<Dictionary<List<string>, string>> list1 = new(){
  new (){{new (){"a"}, "aaa"}, {new (){"a"}, "zzz"}, {new (){"a"}, "yyy"}},
  new (){{new (){"b"}, "bbb"}},
  new (){{new (){"c"}, "ccc"}}
};

我的问题中的 FluentAssertions 错误消息非常具有误导性,因为它们漂亮地打印出某些键丢失了

misses key(s) {{"a"}, {"z"}}
,这与字典中实际键的漂亮打印完全匹配,但它不是被比较的漂亮打印值它是比较的参考位置。如果 FluentAssertions 漂亮地打印出实际比较内容的表示,那就更好了。

请注意,添加 WithStrictOrdering 显着改善了错误消息,与我原始问题中的错误消息相比,并帮助我调试了问题。另一件让我误入歧途的事情是 documentation 中缺少嵌套集合作为示例,我认为这是一个常见的场景。

满足我的需求,以下就足够了:

List<Dictionary<string, List<string>>> list1 = new(){
  new (){{"aaa", new (){"a"}}, {"zzz", new (){"z"}}},
  new (){{"bbb", new (){"b"}}},
  new (){{"ccc", new (){"c"}}},
};
List<Dictionary<string, List<string>>> list2 = new(){
  new (){{"zzz", new (){"z"}}, {"aaa", new (){"a"}}},
  new (){{"bbb", new (){"b"}}},
  new (){{"ccc", new (){"c"}}},
};
List<Dictionary<string, List<string>>> list3 = new(){
  new (){{"zzz", new (){"z"}}, {"aaa", new (){"a"}}},
  new (){{"ccc", new (){"c"}}},
  new (){{"bbb", new (){"b"}}},
};

list1.Should().BeEquivalentTo(list2);  // Matches
list1.Should().BeEquivalentTo(list2, options => options.WithStrictOrdering());  // Matches
list1.Should().BeEquivalentTo(list3);  // Matches
list1.Should().BeEquivalentTo(list3, options => options.WithStrictOrdering());
// Exception:
// Expected list1[1] to contain key "ccc".
// Expected list1[2] to contain key "bbb".
© www.soinside.com 2019 - 2024. All rights reserved.