如果使用Fluent Assertions以不同的顺序断言两个列表是不相等的

时间:2015-03-26 14:35:42

标签: c# tdd fluent-assertions

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

list1.ShouldBeEquivalentTo(list2);

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

如果我们想要按照确切的顺序断言列表,我们可以这样做:

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

如果列表在wrong order中包含相同的对象但我无法找到任何内容,那么我正在寻找断言为假的内容。

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

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

1 个答案:

答案 0 :(得分:1)

编辑:现在我了解戴维要求的内容(请参阅下面的评论)我将代码更新为此解决方案。虽然语法类似,但它不是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
    }
}