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

时间:2013-04-07 23:40:36

标签: c# linq unit-testing

我用LinQ写了一个简单的小组

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失败。 (索引0处的元素不匹配。)

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

2 个答案:

答案 0 :(得分:0)

您的测试失败的原因是:

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

Source

基本上你需要更好地模拟你的第二个系列。我认为这应该有效:

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}
};

答案 1 :(得分:0)

首先 - 你真的不应该从方法中返回匿名类型对象!以后任何地方都很难对这种返回值做任何事情。

我会创建一个名为 Devided 的新结构:

public struct Devided
{
    public int Reminder { get; set; }
    public List<int> Numbers { get; set; }

    public override bool Equals(object obj)
    {
        if(!(obj is Devided))
            return false;

        var d = (Devided)obj ;

        if(object.ReferenceEquals(this, d))
            return true;

        return this.Reminder == d.Reminder && this.Numbers.SequenceEqual(d.Numbers);
    }

    public override int GetHashCode()
    {
        return Reminder;
    }
}

我已覆盖EqualsGetHashCode以使CollectionAssert工作。

使用Devided类,您可以将方法返回类型更改为通用IList<Devided>

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

并断言测试:

[TestMethod]
public void TestMethod1()
{
    IEnumerable<int> numberOfCollection = new List<int> { 5, 14, 9, 8 };
    IList remindernumber = dividedNumbersto5(numberOfCollection);
    IList expectedNumberCollection = new List<Devided>
    {
        new Devided { Numbers = new List<int>() { 5 }, Reminder = 0 },
        new Devided { Numbers = new List<int>() { 8 }, Reminder = 3 },
        new Devided { Numbers = new List<int>() { 14, 9 }, Reminder = 4 }
    };

    CollectionAssert.AreEqual(expectedNumberCollection, remindernumber);
}

如果您愿意,可以仅查看Reminder

var expectedNumberCollection = new List<int> { 0, 3, 4 };

Assert.IsTrue(expectedNumberCollection.SequenceEqual(remindernumber.Select(x => x.Reminder)));