單位測試塊

測試是確保穩定,無錯誤應用程式的絕佳方法。它們充當互動式文件,允許修改程式碼而不用擔心破壞功能。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);
}