【问题标题】:How to assert two lists are not equivalent if in different order using Fluent Assertions如果使用 Fluent Assertions 的顺序不同,如何断言两个列表不等价
【发布时间】:2015-05-30 15:10:50
【问题描述】:

使用Fluent Assertions,我们可以断言两个集合是相等的(在属性值方面),使用如下:

list1.ShouldBeEquivalentTo(list2);

假设list1list2 包含相同的对象in any order,则断言为真。

如果我们想断言列表的顺序是准确的,我们可以这样做:

list1.ShouldBeEquivalentTo(list2, o => o.WithStrictOrdering());

如果列表包含 wrong order 中的相同对象,我正在寻找断言 false 的东西,但我找不到任何东西。

使用 Fluent 断言的最佳方式是什么?

PS - 这是一种学术好奇心,在现实中它甚至可能没有那么有用:)

【问题讨论】:

  • 如果x 有 [5, 6, 8] 而y[5, 6, 7, 8],你想发生什么?它应该被认为是等效的吗?
  • 不,我想断言它是否不是确切顺序中的确切对象。我什至不确定这是否有用,我只是想知道它是否可能。所以这将是错误的,因为第一个列表中不存在 7。

标签: c# tdd fluent-assertions


【解决方案1】:

编辑:现在我了解了 davy 的要求(请参阅下面的评论),我将代码更新为这个解决方案。虽然语法相似,但它不是 FluentAssertion 扩展,但可以通过一些操作来实现。

public static class IEnumerableAssertionExtensions
{
    public static void ShouldContainInWrongOrder<TSubject>(this IEnumerable<TSubject> source, IEnumerable<TSubject> expected)
    {
        var remaining = expected.ToList();
        var inOrder = true;
        foreach (var subject in source)
        {
            if (inOrder && !ReferenceEquals(subject, remaining[0]))
            {
                inOrder = false;
            }
            var s = subject;
            Execute.Verification.ForCondition(() => remaining.Remove(s)).FailWith("Expected item in the collection: {0}", subject.ToString());
        }

        Execute.Verification.ForCondition(() => remaining.Count == 0).FailWith(string.Format("{0} more item{1} than expected found in the list.", remaining.Count, ((remaining.Count == 1) ? string.Empty : "s")));
        Execute.Verification.ForCondition(() => !inOrder).FailWith("list items are ordered identically");
    }
}

[TestClass]
public class TestFoo
{
    class Thing
    {
        public int i;
    }

    [TestMethod]
    public void MyMethod()
    {
        var a1 = new Thing { i=0 };
        var a2 = new Thing { i=1 };
        var a3 = new Thing { i=2 };
        var a4 = new Thing { i=2 };
        var list1 = new List<Thing> { a1, a2, a3 };
        var list2 = new List<Thing> { a1, a2, a3 };
        var list3 = new List<Thing> { a3, a2, a1 };
        var list4 = new List<Thing> { a1, a2, a3, a4 };
        var list5 = new List<Thing> { a3, a2 };

        list1.ShouldContainInWrongOrder(list3); // Succeeds
        list1.ShouldContainInWrongOrder(list2); // Fails
        list1.ShouldContainInWrongOrder(list4); // Fails
        list1.ShouldContainInWrongOrder(list5); // Fails
    }
}

【讨论】:

  • 谢谢,但我正在寻找像 Should().NotContainInOrder() 这样的东西,这样我就可以编写一个测试,当两个列表包含相同的对象但顺序不同时通过。
  • 哦!我明白你现在的要求了。我知道没有直接的 FA 解决方案,但请参阅我在上述答案中的编辑。
猜你喜欢
  • 2018-02-07
  • 2021-10-02
  • 2016-01-13
  • 2017-06-07
  • 2016-05-02
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多