Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Or more generally: to trigger compiler errors in test projects if something that can be checked at compile time is wrong?

share|improve this question
as an approach that shortens time between introducing the bug and discovering it, this looks like worth encouraging – gnat Jan 16 '13 at 12:47
Any time you can turn a runtime exception into a compile time exception is a win - I don't usually make sweeping statements but I can't think of an exceptions to that principle.. – MattDavey Jan 16 '13 at 12:56
@MattDavey - here's one: If it makes the code harder to work on, then the compile time exception isn't worth it. Doesn't come up often, but there are times where trying to make something assertable at compile time makes it much harder to work with. – Michael Kohne Jan 16 '13 at 13:03
@MichaelKohne absolutely, that's a valid point. It's hard to know where the threshold is where a compile-time exception would become unjustifiable.. – MattDavey Jan 16 '13 at 13:52
To add to that - just make sure the compilation error is easy to understand and fix. Sometimes, like when code generators or internal DSLs are involved, the compile errors get so cryptic they have limited value. – Krzysztof Kozielczyk Jan 16 '13 at 18:53
up vote 8 down vote accepted

In principle, why not. A failed test is a failed test regardless of whether it happens at compile time or runtime. Compile time failures can also occur without an explicit static assertion.

On the other hand, if your unit tests are only executed infrequently (shame on you), say every few dozen check-ins, then a compile time check might hinder you in finding out if there are more breakages. That depends on your build structure and how your tests are organised.

share|improve this answer

Yes, it is okay to use static/compile-time assertions in unit tests

In my experience, many developers don't the unit tests enough, although they may compile them. In a complex environment, it is not necessarily possible to run the unit tests on the build machine (environment setup, etc) but you could certainly compile the unit tests. Static assertions would find problems at that point regardless of whether they got run at all.

Also, we've found that it is less intrusive to add the unit tests to the list of objects that need compiling compared to forcing people to compile-then-run a unit test runner before you let them compile/package the main code. Your mileage may vary, of course.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.