提问者:小点点

如何用mockito模拟静态方法做单元测试


我有一个这样的方法。

 public Response post(String json) {

   EventList list = Recorder.getRecorders();
   if (null == list || list.isEmpty()) {
     throw new ServiceUnavailableException("An Recorder is either not configured");
  }
  String targetIUrl = list.getNext().getBase();
  String targetV2Url = targetUrl + "/v2";

 // other processes......
}

>

如果我模拟记录器,是否必须将方法更改为post(字符串json,记录器记录器)?否则,如何使此模拟与该方法交互?


共1个答案

匿名用户

如果要模拟getRecorders()行为而不使用库模拟静态方法(如Powermock),则必须从内部提取静态调用。有几种选择:

>

  • EventList传递到post()

    public post(String json, EventList list) {
        ...
    }
    

    将事件列表注入到包含post()的类中

    public class TheOneThatContainsThePostMethod {
        private EventList eventList;
    
        public TheOneThatContainsThePostMethod(EventList eventList) {
            this.eventList = eventList;
        }
    
        public post(String json) {
            if (null == this.eventList || this.eventList.isEmpty()) {
                throw new ServiceUnavailableException("An Recorder is either not configured");
            }
        }
    }
    

    将静态方法调用隐藏在另一个类中,并将该类的实例注入post()或包含post()的类。例如:

    public class RecorderFactory {
        public EventList get() {
            return Recorder.getRecorders();
        }
    }
    
    public class TheOneThatContainsThePostMethod {
        private RecorderFactory recorderFactory;
    
        public TheOneThatContainsThePostMethod(RecorderFactory recorderFactory) {
            this.recorderFactory = recorderFactory;
        }
    
        public post(String json) {
            EventList list = recorderFactory.getRecorders();
            ...
        }
    }
    
    // Or ...
    
    public post(String json, RecorderFactory recorderFactory) {
        EventList list = recorderFactory.getRecorders();
        ...
    }
    

    使用前两种方法,您的测试可以简单地调用post(),提供(1)一个空的事件列表;(2) 空的事件列表。。。从而允许您测试“抛出503异常”行为。

    使用第三种方法,您可以使用Mockito模拟RecorderFactory的行为,以返回(1)空的事件列表;(2) 空的事件列表。。。从而允许您测试“抛出503异常”行为。