Unit Testing and Documentation

23.1 Built-in unittest

Test runners: unit-threaded (parallel, named tests, mocking), silly, dshould/fluent-asserts (fluent assertions).

Coverage: dmd -cov produces .lst files with line hit counts. dub test --coverage.

int add(int a, int b) { return a + b; }

///                               // documented unittest: shown as an example in docs
unittest
{
    assert(add(2, 3) == 5);
    assert(add(-1, 1) == 0);
}

@("named test") unittest          // UDA name (used by test runners)
{
    import std.exception : assertThrown;
    import std.conv : to, ConvException;
    assertThrown!ConvException("x".to!int);
}
dmd -unittest -main -run mymodule.d     # -main adds an empty main
dub test
dub test -- -v                          # with a test runner such as unit-threaded / silly

23.2 Ddoc Documentation

/**
 * Computes the sum of two integers.
 *
 * Params:
 *     a = first operand
 *     b = second operand
 * Returns: the sum of `a` and `b`
 * Throws: nothing
 * See_Also: $(LREF subtract)
 * Examples:
 * ---
 * assert(add(1, 2) == 3);
 * ---
 */
int add(int a, int b) { return a + b; }
dmd -D -Dd=docs source/*.d          # Ddoc HTML
dub build --build=docs
dub run adrdox -- source/           # nicer docs (as used on code.dlang.org)