Mocking Static Blocks in Java

后端 未结 10 1971
南方客
南方客 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:06

    PowerMock is another mock framework that extends EasyMock and Mockito. With PowerMock you can easily remove unwanted behavior from a class, for example a static initializer. In your example you simply add the following annotations to your JUnit test case:

    @RunWith(PowerMockRunner.class)
    @SuppressStaticInitializationFor("some.package.ClassWithStaticInit")
    

    PowerMock does not use a Java agent and therefore does not require modification of the JVM startup parameters. You simple add the jar file and the above annotations.

提交回复
热议问题