FluentAssertions 是否支持字典的 WithStrictOrdering?

Does FluentAssertions support WithStrictOrdering for dictionaries?

我正在比较两个简单的词典。我以相反的顺序将项目添加到字典中。我在 FluentAssertions 中使用了 WithStrictOrdering 选项,但这个测试通过了,我认为它应该失败:

var actual = new Dictionary<string, string>();
actual.Add("a", "1");
actual.Add("b", "2");

var expected = new Dictionary<string, string>();
expected.Add("b", "2");
expected.Add("a", "1");

actual.Should().BeEquivalentTo(expected, options => options.WithStrictOrdering());

当我在调试器中查看这些词典时,项目的顺序似乎与预期的不同。我可以对列表使用 WithStrictOrdering 选项,它的行为符合预期。 WithStrictOrdering 选项是否适用于字典?

WithStrictOrdering在比较两个字典时被忽略。

在 Fluent Assertions 中,如果满足以下条件,则两个词典被认为是等效的:

  • 两部词典长度相同,
  • 对于期望中的每个键,主题包含该键的值(关于其 comparer),该值 等价于 中相同键的值期望。

找到源代码here

关于您通过调试器观察到的顺序: 元素的顺序可能会改变,例如如果字典是 re-hashed。 通常,您不应依赖 Dictionary.

中元素的顺序

来自documentation

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. The order in which the items are returned is undefined.

如果您仍想根据检索元素的 undefined 顺序比较两个字典中的元素,解决方法是将 Dictionary<string,string> 转换为 IEnumerable<object>

actual.Cast<object>().Should().BeEquivalentTo(expected, options => options.WithStrictOrdering());

注意:在 Fluent Assertions V5 中使用 Cast<KeyValuePair<string, string>>() 也可以,但在即将到来的 V6 中,实现 IEnumerable<KeyValuePair<TKey, TValue>> 的类型被认为是 dictionary-like 类型,因此 Cast<object>() 是使 Should() 解析为 GenericCollectionAssertions 而不是 GenericDictionaryAssertions.

所必需的