D Language Unittesting Unittest blocks


Tests are an excellent way to ensure stable, bug-free applications. They serve as an interactive documentation and allow to modify code without fear to break functionality. D provides a convenient and native syntax for unittest block as part of the D language. Anywhere in a D module unittest blocks can be used to test functionality of the source code.

Yields the sign of a number.
    n = number which should be used to check the sign
    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
    // go ahead and make assumptions about your function
    assert(sgn(10)  ==  1);
    assert(sgn(1)   ==  1);
    assert(sgn(-1)  == -1);
    assert(sgn(-10) == -1);