单位测试块

测试是确保稳定,无错误应用程序的绝佳方法。它们充当交互式文档,允许修改代码而不用担心破坏功能。D 为 unittest 块提供了一种方便的原生语法,作为 D 语言的一部分。D 模块中的任何位置 unittest 块都可用于测试源代码的功能。

/**
Yields the sign of a number.
Params:
    n = number which should be used to check the sign
Returns:
    1 for positive n, -1 for negative and 0 for 0.
*/
T sgn(T)(T n)
{
    if (n == 0)
        return 0;
    return (n > 0) ? 1 : -1;
}

// this block will only be executed with -unittest
// it will be removed from the executable otherwise
unittest
{
    // go ahead and make assumptions about your function
    assert(sgn(10)  ==  1);
    assert(sgn(1)   ==  1);
    assert(sgn(-1)  == -1);
    assert(sgn(-10) == -1);
}