c# - 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!
解决方案
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.
推荐阅读
- r - 从托管在外部服务器上的 Shiny 应用程序访问本地目录结构?
- python - Pyspark:使用 Zeppelin Notebook 在 Hive 中插入表的问题
- figma-api - 如何从 Figma 中的 JSON 文档中获取节点的轮换?
- python - 发送这样的ajax帖子安全吗?如果没有,如何清洗?
- bazel - 为使用 bazel 构建的 py_binary 提交云 ml 引擎作业
- delphi - Firemonkey - TPopUp 内存问题
- c++ - 在 C++ 自定义树的一些迭代后崩溃
- r - 在 R 中,如何测试仅包含某些级别的因子的混合模型中的交互作用?
- python - Tkinter Python 弹出窗口显示消息,但在弹出窗口出现时仍允许另一个函数运行。
- bash - 为什么是 [[ !-f $(find "${mydir}" -maxdepth 1 -name "*.csv" -mtime -1) ]] 居然是真的?