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.

// Block for my function
    assert(myAbs(-1) == 1);
    assert(myAbs(1)  == 1);

This allows straightforward Test-driven development on demand.

Run & execute unittest blocks

unittest blocks can contain arbitrary code which is just compiled in and run when the command line flag -unittest is passed to the DMD compiler. DUB also features compiling and running unittest through the dub test command.

Verify examples with assert

Typically unittests contain assert expressions that test the functionality of a given function. unittest blocks are typically located near the definition of a function which might be at the top level of the source, or even within classes or structs.

Increasing code coverage

Unittest are a powerful weapon to ensure bullet-proof applications. A common measurement to check how much of a program is being covered by tests, is the code coverage. It is the ratio of executed versus existing lines of code. The DMD compiler allows to easily generate code coverage reports by adding -cov. For every module a .lst file, which contains detailed statistics, will be generated.

As the compiler is able to infer attributes for templated code automatically, it is a common pattern to add annotated unittests to ensure such attributes for the tested code:

unittest @safe @nogc nothrow pure
    assert(myAbs() == 1);


rdmd playground.d