可读的序列测试单元测试? [英] Readable unit testing of a yielded sequence?

查看:73
本文介绍了可读的序列测试单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有一些返回IEnumerable<int>对象的方法.此方法使用yield return关键字生成无限序列.斐波那契算法的示例:

Let's suppose I have some method that returns a IEnumerable<int> object. This methods make use of yield return keyword to produce a infinite sequence. Example of the Fibonacci algorithm :

public static IEnumerable<long> Fibonacci()
{
    long x = 0L;
    long y = 1L;
    long z;
    yield return x;
    yield return y;
    while (true)
    {
        z = x + y;
        yield return z;
        y = x;
        x = z;
    }
}

如何为此类序列正确创建单元测试?正确的说我也是可读的.

How can I properly create unit test for such sequence ? By proper I also mean readable.

我可以这样编写单元测试:

I can write unit tests like this :

[TestMethod]
public void FibonacciTest()
{
    var actual = MyClass.Fibonacci();

    var @enum = actual.GetEnumerator();

    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 0);
    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 1);
    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 1);
    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 2);
    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 3);
    Assert.IsTrue(@enum.MoveNext();
    Assert.AreEqual(@enum.Current), 5);
    Assert.IsTrue(@enum.MoveNext();
}

该测试有效,但我认为它不可读.什么是编写序列单元测试的通用准则(斐波纳契逻辑仅是示例)?

This test works, but I don't think it is readable. What are general (Fibonacci alogrithm was only a example) guidelines for writing unit tests for sequences ?

PS:我正在使用Visual Studio OOB测试套件+ Pex.

PS: I'm using Visual Studio OOB Test suite + Pex.

推荐答案

CollectionAssert.AreEqual(new[] {0,1,1,2,3,5}, MyClass.Fibonacci().Take(6).ToList());

这篇关于可读的序列测试单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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