【问题标题】:Does FluentAssertions support WithStrictOrdering for dictionaries?FluentAssertions 是否支持字典的 WithStrictOrdering?
【发布时间】:2021-01-30 04:45:16
【问题描述】:

我正在比较两个简单的字典。我以相反的顺序将项目添加到字典中。我在 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 选项是否适用于字典?

【问题讨论】:

    标签: c# unit-testing dictionary fluent-assertions


    【解决方案1】:

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

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

    • 两个字典的长度相同,并且
    • 对于期望中的每个键,主题包含该键的值(尊重其comparer),该值等效与期望中相同键的值。

    源码在here找到。

    关于您通过调试器观察的顺序: 元素的顺序可能会改变,例如如果字典被重新散列。 一般来说,您不应依赖Dictionary 中的元素顺序。

    来自documentation

    出于枚举的目的,字典中的每个项目都被视为表示值及其键的 KeyValuePair 结构。返回项目的顺序未定义。

    如果您仍想比较两个字典中的元素,尊重检索元素的 undefined 顺序,解决方法是将 Dictionary&lt;string,string&gt; 转换为 IEnumerable&lt;object&gt;

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

    注意:在 Fluent Assertions V5 中使用 Cast&lt;KeyValuePair&lt;string, string&gt;&gt;() 也可以,但在即将到来的 V6 中,实现 IEnumerable&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; 的类型被认为是类字典类型,因此 Cast&lt;object&gt;() 是使 Should() 解析所必需的到GenericCollectionAssertions 而不是GenericDictionaryAssertions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2010-09-17
      • 2011-05-30
      相关资源
      最近更新 更多