我编写了一个从互联网获取数据的程序。
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 测试网络错误。我该怎么做?另外,我的代码好吗?有什么改进建议吗?
最佳答案
你可以这样做:
when(mockUsingNetwork.doSomeNetworkAction()).thenReturn(new SomeNetworkError());
一些网络错误,例如套接字的 ConnectException
对于你的情况,它会是这样的:
URL url = Mockito.mock(URL.class);
when(url.openConnection()).thenThrow(new IOException());
关于java - 如何使用 Mockito 测试网络错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771144/