I don't like the java assert
keyword, because it is not always enabled in production code. I am looking for a good "ProductionAssert" class to use, that always runs the noted assertions.
One candidate is Guava's Preconditions. It's decent, but a bit limited (e.g. no assertEquals()
, assertNull()
, assertGreaterEquals()
).
One alternative is including jUnit or another test framework ... but I'm reluctant to depend upon an entire testing framework just for a simple assert class.
If I were programming in Groovy, I would use PowerAssert.
Is there a good "ProductionAssert" class for Java?
P.S. - one option is to finally check out something like Java Contracts ... but what I'm looking for right now it the absolute minimal, zero friction, just drop-it-in without any changes in the build process kind of class ... I'm not sure contracts fits that description.
In the Java guideline, it is said that "assertions are only intended for debugging and bug hunting, but should be removed in production code". I personally like to write assertions to get notified of invalid program states during testing and let them be deactivated in production.
JUnit assertions are intended to be used in test code, but not in production code. Using JUnit assertions outside of test scope may be confusing.
Contains methods to assert various conditions with test methods, such as whether two values are the same, a condition is true, or a variable is null.
I tend to use Spring's Assert class:
public void thing(String foo){
Assert.hasText(foo, "'foo' is required");
}
Obviously if your not using spring then this isn't going to float your boat and I'm not sure it is much better than guava one.
I would use Junit. Its designed to use these tests.
Another option is to ensure asserts are always turned on. i.e. If you can't control your production environment. You can cause the program to fail if they are not.
boolean assertOn = false;
assert assertOn = true;
if (!assertOn)
throw new AssertionError("Assertions must be turned on");
A third option is to write these methods yourself. There are usually just two lines of code. That way they will do everything you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With