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:
- Attributed unit test
- Documented unit test
@system unittest {// Add the attribute of the function you wanna test}
- In the attributed testing, we use
@systemto verify whether the system is throwing code according to its assigned method.
Code example
Let's look at the code below:
// Declare a functionint subtract(int a, int b) { return a - b; }// Call the build in unittest function@system unittest{ //Define a attribute testingassert(subtract(12,2) == 10);}void main() { }
Code explanation
- Line 2: We define a
subtractfunction in which we subtractbfromaand return the result. - Lines 4 to 8: We declare an attribute test case for the function. We declare a test case for the
subtractfunction 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 functionunittest{ // 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 functionunittest{ // Define the test casededuct 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
deductclass 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 ©2026 Educative, Inc. All rights reserved