xunit.net 中是否有一种简单的方法可以在不考虑项目顺序的情况下比较两个集合? [英] Is there an easy way in xunit.net to compare two collections without regarding the items' order?

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

问题描述

在我的一个测试中,我想确保一个集合具有某些项目.因此,我想将此集合与预期集合的项目进行比较不考虑项目的顺序.目前,我的测试代码看起来有点像这样:

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

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 的 Brad Wilson 在这个 Github 中告诉我问题 应该使用 LINQ 的 OrderBy 运算符,然后使用 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 解决了这个问题,该库提供了许多可以在 fluent 中应用的断言方法风格.当然,还有很多方法可以用来验证集合.

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

此测试通过,因为 BeEquivalentTo 调用忽略了项目的顺序.

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.

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

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