c# - 如何使用单元测试断言 Linq 集合

标签 c# linq unit-testing

我已经用 LinQ 编写了简单的 group by

public IList dividedNumbersto5(IEnumerable<int> NumberOfCollection)
{
    IList reminderNumber = NumberOfCollection.ToList().GroupBy(g => g%5).OrderBy(g=>g.Key)
        .Select(g => new { Numbers = g, Remindar = g.Key}).ToList();
    return reminderNumber;                              
}

当我尝试测试它时,它说第一个索引项与我的期望不匹配。

var groupingoperators = new GroupingOperators();
IEnumerable<int> numberOfCollection = new List<int>{ 5,14,9,8};
IList remindernumber = groupingoperators.dividedNumbersto5(numberOfCollection);
IList expectedNumberCollection = new List<int>{0,3,4};
CollectionAssert.AreEqual(expectedNumberCollection, remindernumber);

CollectionAssert.AreEqual failed. (Element at index 0 do not match.)

我想知道我应该如何为它编写测试。

最佳答案

你的测试失败的原因是因为:

   "Two collections are equal if they have the same elements 
   in the same order and quantity."

Source

Basically you need to mock your second collection a little better. I think this should work:

IList expectedNumberCollection = new List<object>{
 new {Numbers = new List<int>{5},Remindar=0},
 new {Numbers = new List<int>{8},Remindar=3}, 
 new {Numbers = new List<int>{14,9},Remindar=4}
};

关于c# - 如何使用单元测试断言 Linq 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15869180/

相关文章:

c# - 内部异常的单元测试

c# - 修改 Linq 查询以支持可选关系

c# - 从集合的 List<T> 中获取唯一 ID 记录

c# - Process.Start ("IExplore.exe"); <-- 这可靠吗?

c# - 在 C# 中是否有相当于 Java 的标记中断或解决方法

c# - 使用分组依据以删除重复项

python - Django 自动为任意管理表单生成 POST 数据字典

typescript - 如何更新 React/TypeScript 项目中的快照?

c# - 如何在另一个类中获取单例实例

c# - UrlHelper 类在 Asp.net mvc 中抛出空异常