Mocking Static Blocks in Java

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

    I'm not super knowledgeable in Mock frameworks so please correct me if I'm wrong but couldn't you possibly have two different Mock objects to cover the situations that you mention? Such as

    public static class MockClassWithEmptyStaticInit {
      public static void staticInit() {
      }
    }
    

    and

    public static class MockClassWithStaticInit {
      public static void staticInit() {
        System.out.println("static initialized.");
      }
    }
    

    Then you can use them in your different test cases

    @BeforeClass
    public static void setUpBeforeClass() {
      Mockit.redefineMethods(ClassWithStaticInit.class, 
                             MockClassWithEmptyStaticInit.class);
    }
    

    and

    @BeforeClass
    public static void setUpBeforeClass() {
      Mockit.redefineMethods(ClassWithStaticInit.class, 
                             MockClassWithStaticInit.class);
    }
    

    respectively.

提交回复
热议问题