【问题标题】:How to assert (if there are any) duplicates in unit tests?如何在单元测试中断言(如果有的话)重复项?
【发布时间】:2015-05-06 15:14:01
【问题描述】:

我知道

Assert.IsFalse(postsPageOne.Intersect(postsPageTwo).Any());

您可以比较对象以查找任何重复项。

但我想在我的方法中使用它之后检查我的列表是否包含重复项。下面是测试代码:

///ARRANGE
///
var toShuffle = new List<int>(){
    1001,
    1002,
    1003,
    1004,
    1005,
    1006,
    1007,
    1008,
    1009,
    1010
};

///ACT
///
toShuffle = Shared_Components.SharedComponents.Shuffle(toShuffle, 10);

///ASSERT
///
Assert.IsTrue(toShuffle.Count == 10, "Number of Elements not correct!");
Assert.IsTrue(toShuffle.All(a => a >= 1001 && a <= 1010), "Elements out of range!");

【问题讨论】:

  • 你真的应该使用 Assert.AreEqual(10, toShuffle.Count, "Number of Elements not correct!"),而不是 Assert.IsTrue()。这将使您的失败测试报告更加有用。
  • @Grant Winney:Shuffle() 方法改变了每个数字的 [index] 位置。

标签: c# linq list unit-testing stub


【解决方案1】:

也许我的解释不够好和/或示例不恰当。

我是这样解决的:

///ARRANGE
///
var toShuffle = new List<int>(){1001, 1002,1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010};
var expected = new List<int>() { 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010 };

///ACT
///
toShuffle = Shared_Components.SharedComponents.Shuffle(toShuffle, 10);

///ASSERT
///
Assert.AreEqual(10, toShuffle.Count, "Number of Elements wrong!");
Assert.IsTrue(toShuffle.All(a => a >= 1001 && a <= 1010), "Elements out of range!");

//to check if there are any duplicates
toShuffle.Sort();
CollectionAssert.AreEqual(expected, toShuffle, "Duplicates found!");

如果前两个断言为真而最后一个断言失败,则在 1001 - 1010 之间必须至少有一个重复。

【讨论】:

    【解决方案2】:

    下面是如何在 NUnit 中执行此操作(使用较新的断言表示法):

    Assert.That(toShuffle, Is.Unique);

    【讨论】:

      【解决方案3】:

      使用FluentAssertions(我强烈推荐),您可以这样做:

      toShuffle.Should().OnlyHaveUniqueItems();
      

      但是,我实际上会像这样重写你的测试:

      //Arrange
      var original = new List<int>{1001,1002,1003,1004,1005,1006,1007,1008,1009,1010};
      
      //Act 
      var shuffled = Shared_Components.SharedComponents.Shuffle(original , 10);
      
      //Assert
      shuffled.Should().BeEquivalentTo(original)
          .And.NotBeAscendingInOrder();
      

      测试的目的现在更容易理解了。

      【讨论】:

        【解决方案4】:

        查看不同值的数量(toShuffle.Distinct().Count()) 并验证它是否与初始数量相同。

        我还建议您使用正确的断言方法,而不是到处使用Assert.IsTrue()

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-02-22
          • 2021-12-05
          • 1970-01-01
          • 1970-01-01
          • 2018-02-20
          • 1970-01-01
          • 1970-01-01
          • 2015-08-03
          相关资源
          最近更新 更多