简体   繁体   English

如何对返回IEnumerable的方法进行单元测试

[英]How do I Unit Test a method that returns IEnumerable

Please see the code below: 请参见下面的代码:

public IEnumerable<int> Numbers()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
    yield return 5;
}

and the unit test below: 以及下面的单元测试:

public void GetNumbers()
{
    ClassToTest c = new ClassToTest();
    var expected = 
    var actual = c.Numbers();
    CollectionAssert.AreEqual(expected, actual);
}

I need help populating the line that starts: var expected 我需要填充开始的行的帮助: var expected

Do I have to cast to a list for the assert to work. 我必须强制转换为列表才能起作用。 Please notice that order is important ie the two collections must have numbers in the order of: 1,2,3,4,5. 请注意,顺序很重要,即两个集合的编号必须依次为:1、2、3、4、5。

Please note the code above is not a real test. 请注意,上面的代码不是真正的测试。 I have used it to explain my problem. 我用它来解释我的问题。

Try: 尝试:

ClassToTest c = new ClassToTest();

var expected = int[] { 1, 2, 3, 4, 5 };
var actual = c.Numbers().ToArray();

CollectionAssert.AreEqual(expected, actual);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM