断言列表域的独特性 [英] Assert uniqueness of fields in list

查看:210
本文介绍了断言列表域的独特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在C#中的列表和我想要做一个测试,看看是否ID字段的所有值都是唯一的。

I have made a list in C# and I want to make a test to see if all the values of the Id fields are unique.

public static List<RestaurantReview> _reviews = new List<RestaurantReview>
{
    new RestaurantReview
    {
        Id = 1,
        Name = "McDonalds",
    },
    new RestaurantReview
    {
        Id = 2,
        Name = "Burger King",
    },
}

由于我做了一些调试我发现那位指出,它正在运行低谷列表中,但我没有得到正确的测试值。可能有人请解释什么,我做错了什么?

Because I did some debugging I fount out that it is running trough the list but I do not get the proper test value. Could someone please explain what I am doing wrong here?

[TestMethod()]
public void CheckReviewIds()
{
    var FirstReview = ReviewsController._reviews.First();
    bool AllUniqueIds = ReviewsController._reviews.All(s => s.Id == FirstReview.Id);

    Assert.IsFalse(AllUniqueIds);

}

提前

感谢。

Thanks in advance.

推荐答案

您正在检查所有值不等于第一个。这可以是这种情况,如果值是例如 [1,2,3,3 ],没有一个是等于第一但本身,而是 3 == 3

You're checking that all values are not equal to the first. This can be the case if the values are for example [1, 2, 3, 3], none are equal to the first but itself, but 3 == 3.

相反,你可以 GROUPBY 通过数值组他们,然后检查它们是不同的。我假设的表现是不是在这里一个大问题(是这样的话,如果该列表是小于100000物品我假设):

Instead, you can GroupBy to group them by value and then check that they are distinct. I'm assuming performance isn't a big issue here (that's the case if the list is less than 100000 items which I assume):

 ReviewsController._reviews.GroupBy(x => x.Id).Count() == ReviewsController._reviews.Count; 






请注意,这可能不是最好的主意测试组件的内部状态,而不是测试它被暴露的API。否则,你通过你的单元测试定义合同是由您的实现细节的限制。这最后一段是刚上虽然人的意见。


Note that it might not be the best idea to test the internal state of a component, instead test the API it is exposing. Otherwise, the contract you define through your unit tests is limited by your implementation detail. This last paragraph is just on man's opinion though.

这篇关于断言列表域的独特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆