如何用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......
}
  1. 我想模拟Recorder.getRecorder((并做一些类似when(Recorder.getRecord(((的事情。然后返回(null(并测试是否抛出503异常。但是getRecorder((是一个静态方法。我知道Mockito不能模拟静态方法,但我仍然想知道是否可以在不使用Powermock或其他库的情况下更改一些代码,使其可测试。

  2. 如果我模拟Recorder,我是否必须将方法更改为post(Stringjson,Recorder-Recorder(?否则,我如何使这个mock与该方法交互?

如果您想在不使用用于模拟静态方法的库(如Powermock(的情况下模拟getRecorders()行为,则必须从post()内部提取静态调用。有几个选项:

  1. EventList传递到post()

    public post(String json, EventList list) {
    ...
    }
    
  2. EventList注入到包含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");
    }
    }
    }
    
  3. 将静态方法调用隐藏在另一个类中,并将该类的实例注入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(一个空EventList;(2( 一个空的CCD_ 11。。。从而允许您测试"抛出503异常"行为。

使用第三种方法,您可以使用Mockito来模拟RecorderFactory的行为,以返回(1(一个空EventList;(2( 一个空的CCD_ 14。。。从而允许您测试"抛出503异常"行为。

最新更新