Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A good assert class for production use? Java's equivalent of Groovy's PowerAssert?

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.

like image 479
ripper234 Avatar asked Feb 07 '12 12:02

ripper234


People also ask

Should I use assert in production?

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.

Should you use asserts in production code?

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.

What is an assert class?

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.


2 Answers

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.

like image 169
Gareth Davis Avatar answered Oct 21 '22 17:10

Gareth Davis


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.

like image 28
Peter Lawrey Avatar answered Oct 21 '22 18:10

Peter Lawrey