TestSetup is a JUnit class you can use if you want to introduce initialization in your JUnit tests that only get invoked once, and not once before test method, which is what JUnit does (making it difficult to make sure that an initialization method is only invoked once during the lifetime of the class). I wrote more about this oddity not long ago.

A recent weblog entry about TestSetup shows how to use it, which is pretty straightforward. I still have a big problem with this solution, and what JUnit forces you to do to work around this “design choice”: it forces you to introduce static methods in your code.

I don’t have anything against static methods in general, I tend to use them as much as possible whenever they don’t need access to any non-static fields since it decreases the coupling between my classes. However, static methods are particularly evil when they modify state, and by extension, force you to declare static fields.

Which is exactly the only choice that JUnit leaves you.

The problem with non-const static methods is that they break badly in several cases:

  • Multi-thread access.
  • Different objects thinking they are accessing private content, while it is actually shared.
  • Reuse of the same JVM.

This last point is particularly important. By forcing you to introduce static methods in your code, JUnit guarantees that if somebody ever invokes your class several times from an ant task while not providing the flag fork=”yes”, your code will break in mysterious ways.

Classes in object-oriented programming obey very simple rules:

  • If you invoke your initialization from the constructor, it will only be invoked once.
  • If your content is not static, it is guaranteed to be private to your instance.

JUnit violates these two principles and I just can’t get used to it. Instead of righting a wrong with another wrong, why not return to the most intuitive way of doing this and letting test writers implement methods that are guaranteed to be invoked once?

Of course, these is also an alternative. 🙂