如何使用Mockito测试Netword错误?

时间:2018-12-13 22:46:04

标签: java unit-testing junit mockito

我写了一个程序,可以从Internet上获取数据。

public class GetDataService {

  public List<String> getData()  {
    List<String> lines = new ArrayList<>();
    try {
    URL url = new URL("http://worldtimeapi.org/api/ip.txt");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null) {
      String a = line;
      lines.add(a);
      }
      bufferedReader.close();

    } catch (IOException ex) {
      throw new RuntimeException("Can not making the request to the URL.");
    }
    return lines;
  }
}

现在,我想使用Mockito测试网络错误。我该怎么做?另外,我的代码好吗?有任何改进建议吗?

1 个答案:

答案 0 :(得分:1)

您可以这样:

when(mockUsingNetwork.doSomeNetworkAction()).thenReturn(new SomeNetworkError());

SomeNetworkError,例如套接字的ConnectException

对于您的情况,它将类似于:

    URL url = Mockito.mock(URL.class);
    when(url.openConnection()).thenThrow(new IOException());