Assertions in Java

It was not until recently that I found this feature of the Java language. Runtime assertions, which can be enabled or disabled with JVM arguments, and derive in errors if failed.

Such a feature can be very helpful in building quality Classes. In some way, when enabled, every object built with assertions in its code is testing itself all the time.

Added to that, the way this feature is implemented seems the right one. Sun states that assert statements are costless when not enabled, so there’s no reason to skip an assertion. They also rise an Error when triggered, which will totally discourage even the boldest of coders from attempting to catch it.

The issue that rises after this thoughts is, when to unit test and when to assert?

As I said a few lines ago, I’m totally new at this assert thing. But I imagine assertions in the code I’ll write from now on, in many, many places.

In my opinion, Unit Testing is useful to validate behavior given a specific use case. And for this matter, an assertion is also valid. But, as well, Unit Tests will be processed with a given, known input. This is where assertions come in handy. They should be used in production-like environments, where most corner cases may arise.

This is why I believe asserts should be used together with Unit Tests (asserting that which will be tested), and beyond: asserting even that which you may not test, perhaps because of laziness or time constraints; or because you don’t see any possible way in which a given Object might be null, but…

One more, important thing: every pre-Production environment should have assertions enabled. Production will then see a much more robust application. If this is not accomplished, asserts loose their most of their value.