【问题标题】:Fluent Assertions: Equivalency of two lists of arrays, with arrays needing strict orderingFluent Assertions:两个数组列表的等价性,数组需要严格排序
【发布时间】:2021-10-02 06:15:06
【问题描述】:

我正在尝试使用 Fluent Assertions 来测试置换生成算法。该算法生成一个List<int[]>,其中List 的顺序无关紧要,但每个int[] 的元素都可以。

[Fact]
public void Are_all_permutations_generated()
{
    // Arrange
    var expected = new List<int[]>
    {
        new[] { 1, 2, 3 },
        new[] { 1, 3, 2 },
        new[] { 2, 1, 3 },
        new[] { 2, 3, 1 },
        new[] { 3, 1, 2 },
        new[] { 3, 2, 1 }
    };

    // Act
    var result = new List<int[]>
    {
        new[] { 3, 2, 1 },
        new[] { 1, 3, 2 },
        new[] { 2, 3, 1 },
        new[] { 2, 1, 3 },
        new[] { 3, 1, 2 },
        new[] { 1, 2, 3 }
    };

    // Assert
    result.Should().BeEquivalentTo(expected);
}

如果我在上面的代码块中使用result.Should().BeEquivalentTo(expected),即使result 是,它也会通过

var result = new List<int[]>
{
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3 },
    new[] { 1, 2, 3 }
};

我如何编写 Fluent Assertions 以允许列表的任何顺序,但对数组有严格的顺序,以便它可以断言所有排列都已找到?有没有办法在BeEquivalentTo 中写options 来做到这一点?

【问题讨论】:

    标签: c# unit-testing fluent-assertions


    【解决方案1】:

    使用WithStrictOrderingFor 确定何时要使用严格排序。它需要一个 lambda,让您可以访问 IObjectInfo,这是一个公开您可以使用的各种相关信息的对象。类似的东西

    WithStrictOrderingFor(info => info.RuntimeType == typeof(int[]))
    

    【讨论】:

      【解决方案2】:

      您可以尝试在数组断言上使用WithStrictOrdering

      例如:

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

      您也可以查看来自 FluentAssertion 的 collection assertion docs,它们提供了更多关于如何比较集合的选项。

      【讨论】:

      • 这对父 List 和子数组都进行了严格的排序。我想要 List 上的任何顺序,并且只对数组元素进行严格的排序。
      猜你喜欢
      • 2015-05-30
      • 1970-01-01
      • 2016-01-13
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多