This is the homepage of Peter Alexander. I am currently at Facebook working on AR/VR. Any opinions are my own.
Recent Posts
- Single-Threaded Parallelism
- unique_ptr Type Erasure
- The Condenser Part 1
- Cube Vertex Numbering
- Range-Based Graph Search in D
All Posts
Links
github.com/Poita@Poita_
Atom Feed
D Tip - Skipping main() for Unit Tests
When you compile a D program with unit tests enabled (using the -unittest
flag), the generated executable will first run the unit tests then continue
with executing main()
.
Sometimes, you just want the unit tests to run in isolation.
A simple way to skip execution of main()
for unit test builds is to use
the unittest
version identifier:
unittest
{
assert(1 + 1 == 2, "Something horrible has gone wrong.");
}
void main()
{
version(unittest)
return;
// This won't be run
}
Code inside the version(unittest)
block will only be run when the code is
compiled with -unittest
, so the code above will exit main()
immediately
in unit test builds.
There are numerous pre-defined version identifiers, which you can find at
http://dlang.org/version.html.
Another handy one is version(assert)
, which is only compiled in when asserts
are enabled.