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.
Stephen c
source share