Mocking Static Blocks in Java

后端 未结 10 1975
南方客
南方客 2021-01-30 11:00

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

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 11:20

    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.

提交回复
热议问题