Search code examples
c#linqlistunit-testingstub

How to assert (if there are any) duplicates in unit tests?


I know with

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

you can compare to objects to find any duplicates.

But I want to check if my list contains duplicates, after I used it in my method. Here is the test code:

///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!");

Solution

  • Using FluentAssertions (which I highly recommend), you can do:

    toShuffle.Should().OnlyHaveUniqueItems();
    

    But, I'd actually rewrite your test like this:

    //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();
    

    The purpose of the test is now much easier to understand.