首页 > 解决方案 > How to test if two collections of objects are in a different order based on one of the objects' properties?

问题描述

I'm reasonably new to unit testing and I'm running into a problem. I have two collections (decks) holding objects (cards), with the cards being objects that have an ID, value, suit etc.

I'm writing a unit test to see if my Shuffle() method works, so I want to test if an unshuffled deck (which creates 52 cards with IDs 0-51) and a shuffled deck are in the same order or not. Obviously, the cards are unique objects, even if they hold the same values. So by definition, testing to see if they're the same will always result in false. I'm very, very new to NUnit (just installed it two days ago) and I'm still struggling with the syntax here and there.

Ideally, I'd want an assertion to check if the order of both collections is the same, with the order being determined by the cards' IDs because, as objects, they are all unique and therefore always in a different order. Now, I can check if the shuffled deck is no longer ordered by ID, but that would be a bad unit test since it assumes that an unshuffled deck is always ordered by ID. I can also check the unshuffled deck, but it seems rather inelegant to test it that way without actually comparing the two decks.

I also want an assertion to check that my deck constructor creates only unique IDs, but again, all objects in the collection are always unique but I don't know the syntax (if it exists) for checking for uniqueness of one specific property of all the cards.

I've been Googling like crazy, and I've been trying a lot of different syntax things by brute force, but I'm at a loss now. I hope you guys can help me, thanks in advance!

标签: c#unit-testingobjectnunit

解决方案


You can use SequnceEqual with LINQ Select like that:

class Card
{
    public int CardId { get; set; }
}

Assert.IsTrue(new[] { new Card {CardId = 1}, new Card {CardId = 2}}
        .Select(c => c.CardId)
        .SequenceEqual(new[] {1,2}));

Also I would recommend to check out Fluent Assertions library, sometimes it is not very obvious how to do things there but in general it has some very useful features.


推荐阅读