Mocking Static Blocks in Java

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

    This is going to get into more "Advanced" JMockit. It turns out, you can redefine static initialization blocks in JMockit by creating a public void $clinit() method. So, instead of making this change

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

    we might as well leave ClassWithStaticInit as is and do the following in the MockClassWithStaticInit:

    public static class MockClassWithStaticInit {
      public void $clinit() {
      }
    }
    

    This will in fact allow us to not make any changes in the existing classes.

提交回复
热议问题