How to mock with static methods?

后端 未结 7 1066
星月不相逢
星月不相逢 2020-12-05 02:31

I\'m new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.

The problem I\'m having is that in my data acce

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-05 02:48

    A simple solution is to allow to change the static class's implementation via a setter:

    class ClassWithStatics {
    
      private IClassWithStaticsImpl implementation = new DefaultClassWithStaticsImpl();
    
      // Should only be invoked for testing purposes
      public static void overrideImplementation(IClassWithStaticsImpl implementation) {
         ClassWithStatics.implementation = implementation;
      }
    
      public static Foo someMethod() {
        return implementation.someMethod();
      }
    
    }
    

    So in the setup of your tests, you call overrideImplementation with some mocked interface. The benefit is that you don't need to change clients of your static class. The downside is that you probably will have a little duplicated code, because you'll have to repeat the methods of the static class and it's implementation. But some times the static methods can use a ligther interface which provide base funcionality.

提交回复
热议问题