是否有xunit.net一个简单的方法不考虑项目'为了比较两个集合? [英] Is there an easy way in xunit.net to compare two collections without regarding the items' order?

查看:205
本文介绍了是否有xunit.net一个简单的方法不考虑项目'为了比较两个集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的测试之一,我希望确保集合具有一定的项目。所以,我想这个集合与预期集合的项目比较不是关于项的顺序。目前,我的测试code看起来有点像这样的:

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 regarding the order of the items. Currently, my test code looks somewhat like this:

[Fact]
public void SomeTest()
{
    // Do something in Arrange and Act phase to obtain a collection
    List<int> actual = ...

    // Now the important stuff in the Assert phase
    var expected = new List<int> { 42, 87, 30 };
    Assert.Equal(expected.Count, actual.Count);
    foreach (var item in actual)
        Assert.True(expected.Contains(item));
}

有没有更简单的方法在xunit.net实现这一目标?我不能使用 Assert.Equal ,因为这方法检查项目的顺序是两个集合相同。我有一个看看 Assert.Collection 但是,这并不删除 Assert.Equal(expected.Count,actual.Count)在code上述表示的。

Is there any easier way to achieve this in xunit.net? I can't use Assert.Equal as this method checks if the order of the items is the same in both collections. I had a look at Assert.Collection but that doesn't remove the Assert.Equal(expected.Count, actual.Count) statement in the code above.

感谢提前你的答案。

推荐答案

布拉德·威尔逊xunit.net告诉我在这个 Github上问题一个人应该使用LINQ的排序依据运营商和事后 Assert.Equal 来验证两个集合包含相等项目不考虑它们的顺序。当然,你必须有可以使用在首位订购(我真的没有在我的情况)对应的项目类的属性。

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).

就个人而言,我使用 FluentAssertions ,它提供了很多可以在一个流畅的应用断言方法库解决了这个问题样式。当然,也有很多方法,你可以用它来验证集合

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.

在我的问题的情况下,我会使用类似如下的code:

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);
}

该测试通过,因为 BeEquivalentTo 通话忽略了项目的顺序。

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

Shouldly 也是,如果你不想去FluentAssertions一个不错的选择。

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

这篇关于是否有xunit.net一个简单的方法不考虑项目'为了比较两个集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆