How to mock with static methods?

后端 未结 7 1084
星月不相逢
星月不相逢 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:54

    I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework.

    i.e. in your class with the static method have:

    private static final MethodObject methodObject = new MethodObject();
    
    public static void doSomething(){
        methodObject.doSomething();
    }
    

    and your method object can be a very simple, easily-tested:

    public class MethodObject {
        public void doSomething() {
            // do your thang
        }
    }
    

提交回复
热议问题