Tests are an excellent way to ensure stable, bug-free applications.
They serve as an interactive documentation and allow the modification
of code without fear of breaking functionality. D provides a convenient
and native syntax for unittest blocks 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
unittest
{
assert(myAbs(-1) == 1);
assert(myAbs(1) == 1);
}
This allows straightforward Test-driven development on demand.
unittest blocksunittest 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.
assertTypically 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.
Unit tests 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 makes generating code coverage reports easy
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:
@safe @nogc nothrow pure unittest
{
assert(myAbs() == 1);
}