Is there an easy way in xunit.net to compare two collections without regarding the items' order?

后端 未结 5 513
借酒劲吻你
借酒劲吻你 2021-01-01 11:08

In one of my tests, I want to ensure that a collection has certain items. Therefore, I want to compare this collection with the items of an expected collection not r

5条回答
  •  不思量自难忘°
    2021-01-01 11:43

    Brad Wilson from xunit.net told me in this Github Issue that one should use LINQ's OrderBy operator and afterwards Assert.Equal to verify that two collections contain equal items without regarding their order. Of course, you would have to have a property on the corresponding item class that you can use for ordering in the first place (which I didn't really have in my case).

    Personally, I solved this problem by using FluentAssertions, a library that provides a lot of assertion methods that can be applied in a fluent style. Of course, there are also a lot of methods that you can use to validate collections.

    In the context of my question, I would use something like the following code:

    [Fact]
    public void Foo()
    {
        var first = new[] { 1, 2, 3 };
        var second = new[] { 3, 2, 1 };
    
        first.Should().BeEquivalentTo(second);
    }
    

    This test passes because the BeEquivalentTo call ignores the order of the items.

    Shouldly is also a good alternative if you do not want to go with FluentAssertions.

提交回复
热议问题