In the last article, I briefly explained how D language has built-in support for performing unit tests. I feel this is an advantage over many current languages.
What if we want to run only a subset of unit tests? Although it is a good idea to run the unit tests every time there is a change in the code, if the project is large, running all the tests every time might be an overhead and not necessary too.
In a real project, we might have separate unit tests for function definitions, classes and so on. Let us suppose that at a certain point in time, we wish to test just the function unit tests, ignoring class unit tests or the other way. How do we achieve this?
First, here is sample D code that defines a function “findMax” and a class “BankAccount” along with respective unit test blocks:
As before, we enable “unittest” in the Project properties:
When we build and run the program, the output is as expected (remember, only the unit tests are run):
What we have seen above is the normal way to run unit tests. Let us now get back to our earlier question: How to run only the unit test block that tests the function “findMax”?
It would have been nice if D language allowed “named” unit test blocks like so:
If this were possible, then we might be able to specify which “named” tests must be run. Unfortunately, this won’t work and it results in compiler error!
So what is the other option? Here is where “version” feature of the language comes in handy. It is a compiler (preprocessor) feature that can be used to include or exclude code fragments. It allows us to wrap unit test blocks in suitable “version” tags. In our case, we can do the following:
Note that for convenience, I have grouped the unit test blocks together.
Now, we can enable only the “function_unit_test” block this way:
When we build the project now and run it, this is what we get:
Similarly, we can enable “class_unit_test” if we want. Hope you get the idea.
But what if we want “all” the unit tests to run? It would be tedious to enable all version tags individually. This is where “version assigment” feature comes in handy:
We can then enable “all_tests” version tag and this automatically takes care of including the full set of unit tests (or whatever have been assigned):
When we build and run the program, both the unit test blocks are executed:
This is quite convenient, isn’t it? Of course, nothing prevents us from grouping different unit tests using different version tags accoding to our requirement. What I have discussed above is just an example.
Ideally, of course, I would prefer “named” unit test blocks as hinted earlier. Hope the language designers introduce such a feature in future!
Here is the source code used in this example.
Have a wonderful week!
Recent Comments