JUnit - Static classes maintain state between test classes?

I have a unit test class that runs individually on startup. When I run it with all the other tests in the package, it fails because the failure is that the independent static class was not initialized. This independent static class is used by other classes, and therefore it seems that its state is maintained between tests.

Is my observation correct or is something else happening? It would also be nice if someone could provide a link or something as a link.

Thanks!

+7
java junit
source share
2 answers

This independent static class is used by other classes, and therefore it seems that its state is maintained between tests.

Yes. Here is what will happen. And this is just one of the reasons why static is uncomfortable.

Static fields exist for the lifetime of the classes that define them, and this usually means the lifetime of the JVM. I tried to find a place in JLS where this is explicitly stated. The closest I could find was JLS 8.3.1.1 which says:

"If a field is declared static, there is exactly one incarnation of the field, regardless of how many instances (possibly null) of the class can ultimately be created. A static field, sometimes called a class variable, is embodied when the class is initialized (Β§12.4)."

Elsewhere, JLS says that a class is initialized only once.

The exception is when the class is unloaded, but this will not happen. Or at least not the normal / standard behavior of JUnit. (But it can be done: see Using different classloaders for different JUnit tests? )

And in case you are worried, there is no JUnit β€œmagic” to reset statics in their original state (no matter how you define it). It is too complicated (and terrible) to consider implementing this.

+5
source share

The methods have no state (except that this method is launched, of course), so no one is saved between invocations - even for static methods.

Any static field retains its state for the duration of the JVM (unless, of course, the code does not change its value). JUnit uses a single JVM for all of its tests, so yes, static fields maintain state between tests.

This is one of the main reasons people do not recommend using static fields where they can be avoided: this reduces the amount of global state you need to worry about, and therefore greatly facilitates the reasoning about tests.

+4
source share

All Articles