加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在xunit.net中有一个简单的方法来比较两个集合,而不考虑项

发布时间:2020-12-15 07:39:04 所属栏目:百科 来源:网络整理
导读:在我的一个测试中,我想确保一个集合有一些项目.因此,我想将此集合与预期集合的项目进行比较,而不是关于项目的顺序.目前,我的测试代码看起来像这样: [Fact]public void SomeTest(){ // Do something in Arrange and Act phase to obtain a collection Listin
在我的一个测试中,我想确保一个集合有一些项目.因此,我想将此集合与预期集合的项目进行比较,而不是关于项目的顺序.目前,我的测试代码看起来像这样:
[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)语句.

感谢您的答案提前.

解决方法

来自xunit.net的Brad Wilson在 Github Issue号告诉我,应该使用LINQ的OrderBy运算符,然后使用Assert.Equal来验证两个集合是否包含相同的项目而不关于它们的顺序.当然,您必须在相应的项目类上有一个属性,您可以首先使用它来排序(在我的情况下我真的没有).

就个人而言,我通过使用FluentAssertions,解决了这个问题,该库提供了很多可以流利的风格应用的断言方法.当然,there are also a lot of methods that you can use to validate collections.

在我的问题的上下文中,我将使用如下代码:

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

    first.Should().BeEquivalentTo(second);
}

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

Shouldly也是一个很好的选择,如果你不想与FluentAssertions一起去.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读