How to write unit tests in D

Overview

Unit testing is one of the most essential processes of application development in which we test a particular part of the code of the application to see if it's working correctly or not.

In the D language, we use a built-in function called unittest to test whether a particular part of the code is working correctly or not.

Syntax

unittest
{
//code you want to test
}
Syntax of unit testing in D programming language
  • At first, we use a built-in function called unittest and pass the test case within the curly bracket we want to test.

Example

class multiply
{
int mul(int x, int y) { return x * y; }
// Call the build in unittest function
unittest
{ // Define the test case
multiply m = new multiply;
assert(m.mul(3,12) == 36);
}
}
void main() {
}

Explanation

  • Line 5: We use a built-in unittest function and provide the test case within the curly bracket.
  • Lines 6–9: We code the test case. If the test passes the correct result, then it shows an output that says 1 modules passed unittests. But if the test passes the wrong result, it shows modules FAILED unittests in the output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved