www.digitalmars.com

D Programming Language 1.0


Last update Sun Dec 30 20:34:44 2012

Unit Tests

UnitTest:
	unittest FunctionBody

Unit tests are a series of test cases applied to a module to determine if it is working properly. Ideally, unit tests should be run every time a program is compiled.

Unit tests are a special function defined like:

unittest {
  ...test code...
}

There can be any number of unit test functions in a module, including within struct, union and class declarations. They are executed in lexical order. Stylistically, a unit test for a function should appear immediately following it.

A compiler switch, such as -unittest for dmd, will cause the unittest test code to be compiled and incorporated into the resulting executable. The unittest code gets run after static initialization is run and before the main() function is called.

For example, given a class Sum that is used to add two values:

class Sum {
  int add(int x, int y) { return x + y; }

  unittest
  {
    Sum sum = new Sum;
    assert(sum.add(3,4) == 7);
    assert(sum.add(-2,0) == -2);
  }
}

Versioning

The version identifier unittest is predefined if the compilation is done with unit tests enabled.





Forums | Comments |  D  | Search | Downloads | Home