I'm trying to unit test a class that references static data from another class. I cannot "not" use this static class, but obviously running multiple tests has become problematic. So my question is this. Is there a way in a junit test to reinitialize a static class? That way one test is not effected by a previous test?
So in other words some way of doing this:
Foo.setBar("Hello");
// Somehow reinitialize Foo
String bar = Foo.getBar(); // Gets default value of bar rather than "Hello"
Unfortunately, I cannot change Foo, so I'm stuck using it.
Edit It appears I made my example a bit too simple. In the real code "Bar" is set by a system property and gets set to an internal static variable. So once it starts running, I can't change it.
You could use PowerMock (with Mockito) or JMockit to mock the static class to have it do whatever you want in each test.
Three suggestions,
Call the static method from the
@Before
setting it to some known value.Use
ReflectionTestUtils
to set the value via reflection.Update your code to have a instance wrapper class that wraps the call to the static method in an instance method / class. Mock the wrapper and inject into your class under test.
I would use
Factory
pattern withinit
anddestroy
static methods that should take care about all instances.Something like:
So per unitest enough to run:
If you use PowerMock, you can mock static methods -- which is what you should do.
Here is a little example where a utility class using static initializer is re-loaded to test initialization of that utility. The utility uses a system property to initialize a static final value. Normally this value cannot be changed at runtime. So the jUnit-test reloads the class to re run the static initializer…
The utility:
The jUnit-test:
Though it was a bit dirty, I resolved this by using reflections. Rather than rerunning the static initializer (which would be nice), I took the fragile approach and created a utility that would set the fields back to known values. Here's a sample on how I would set a static field.