Unittest

From D Wiki
Revision as of 21:40, 14 December 2012 by Quickfur (talk | contribs) (Created page with "==Usage== D has a simple but very useful construct, the '''unittest''' block. For example: <syntaxhighlight lang=D> real complicatedComputation(real[] args) { real resul...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Usage

D has a simple but very useful construct, the unittest block. For example:

real complicatedComputation(real[] args)
{
    real result;
    result = /* perform some fancy computation here */;
    return result;
}

unittest
{
    // Test complicatedComputation by calling it with arguments that
    // produce a known result
    auto knownArguments = [
        1.0, 1.61803, 2.71828
    ];
    auto result = complicatedComputation(knownArguments);

    // Check that the result is what you expected
    enum expectedAnswer = 3.14159;
    enum tolerance = 1e-12;
    assert(abs(result - expectedAnswer) < tolerance);
}

Code in this block is not executed at runtime unless you run DMD with the -unittest command-line option. Programs compiled with the -unittest option will run all unittests in the program first, before the main() function is entered. This allows you to write unittests for your code within the source file itself, thus making it more conducive for encouraging programmers to write unittests.

Advantages

  • You don't have to implement your own unittesting framework, as DMD provides it for free.
  • You don't have to switch over to another unittesting system, and possibly write the testing code in a different language.
  • You can write unittests to check for corner cases while your code is still fresh in your mind, rather than later when you may have forgotten about these corner cases.
  • You can even write unittests first, and then write the code to implement the feature being tested until all unittests passed, after which you know that your code is ready to use.
  • If you make a code change that introduces a bug in previously-working code, your program will refuse to start until the failing unittest is addressed. This reduces regressions in your code.
  • It's so easy to write unittests in D that you should be ashamed to write code without any unittests!

Placement

The important question is, where to put these unittest blocks?

At the end of the file

One way to avoid cluttering real code with long unittest blocks is to collect all unittests at the end of the source file. This has the advantage of keeping the actual code in one place.

Following the code being tested

Another convention is to place unittests immediately after the function or class that it's testing. This has the advantage of ... TBD