2

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

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

4

2 回答 2

0

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

   “如果两个集合具有相同的元素,则它们是相等的
   以相同的顺序和数量。”

来源

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

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}
};
于 2013-04-08T00:00:47.443 回答
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如果您愿意,您可以只检查s:

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

Assert.IsTrue(expectedNumberCollection.SequenceEqual(remindernumber.Select(x => x.Reminder)));
于 2013-04-08T06:08:34.543 回答