What are the types of unit tests in D?

Overview

Unit testing is an essential element of the application development process in which we test a specific section of the application's code to see that it's working correctly.

In D programming language, there are two types of unit testing:

  1. Attributed unit test
  2. Documented unit test

Types of unit test in D

Attributed testing

The attributed testing is used to test the particular functionality of the function by calling them in the test case and then checking the result to verify whether the function is working correctly.

Syntax

@system unittest {
// Add the attribute of the function you wanna test
}
  • In the attributed testing, we use @system to verify whether the system is throwing code according to its assigned method.

Code example

Let's look at the code below:

// Declare a function
int subtract(int a, int b) { return a - b; }
// Call the build in unittest function
@system unittest
{ //Define a attribute testing
assert(subtract(12,2) == 10);
}
void main() { }

Code explanation

  • Line 2: We define a subtract function in which we subtract b from a and return the result.
  • Lines 4 to 8: We declare an attribute test case for the function. We declare a test case for the subtract function by using @system unittest.

Documented testing

In documented testing, we first implement the test case on a particular function and then implement testing on the program by executing the program in the test case to verify that the example used for the function is correct or not.

Syntax

lass deduct
{
int de(int x, int y) { return x - y; }
// Call the build in unittest function
unittest
{ // Define the test case
}
}
unittest
{
//Define the test case on implemented program
}
void main() {
}

Code example

Let's look at the code below:

class deduct
{
int de(int x, int y) { return x - y; }
// Call the build in unittest function
unittest
{ // Define the test case
deduct d = new deduct;
assert(d.de(12,3) == 9);
}
}
unittest
{
auto t = new deduct();
auto test = t.de(12,3);
}
void main() {
}

Code explanation

  • Lines 5 to 9: We define the test case for the deduct class function.
  • Lines 11 to 15: We implement one more test case to test if the example we used in the program is correct.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved