My motto for Java is \"just because Java has static blocks, it doesn\'t mean that you should be using them.\" Jokes aside, there are a lot of tricks in Java that make testing a
Occasionally, I find static initilizers in classes that my code depends on. If I cannot refactor the code, I use PowerMock's @SuppressStaticInitializationFor
annotation to suppress the static initializer:
@RunWith(PowerMockRunner.class)
@SuppressStaticInitializationFor("com.example.ClassWithStaticInit")
public class ClassWithStaticInitTest {
ClassWithStaticInit tested;
@Before
public void setUp() {
tested = new ClassWithStaticInit();
}
@Test
public void testSuppressStaticInitializer() {
asserNotNull(tested);
}
// more tests...
}
Read more about suppressing unwanted behaviour.
Disclaimer: PowerMock is an open source project developed by two colleagues of mine.