单元测试中未涵盖的 catch 块
catch block not covered in unit testing
我已经写了异常通过的测试用例,但是没有覆盖代码覆盖。
请帮帮我,我试了很多方法都没有解决。
public String checkJiraStatus(HttpURLConnection httpURLConnection) throws IOException {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
}
in.close();
JSONObject jsonObject = new JSONObject(String.valueOf(stringBuilder));
JSONObject fields = (JSONObject) jsonObject.get("fields");
JSONObject status = (JSONObject) fields.get("status");
return (String) status.get("name");
}catch (IOException |JSONException ioException) {
throw new IOException("Problem while fetching the data"+ioException.getMessage());
}
}
测试用例正确通过但没有给出代码覆盖率。
@Test(expected = Exception.class)
public void testIoException() throws Exception {
when(mockJiraFunctions.checkJiraStatus(any())).thenThrow(new
IOException("Problem while fetching the data"));
jiraFunctions.checkJiraStatus(any());
}
正如我在评论中提到的,您应该 运行 您的真实方法才能获得报道。
并且您应该创建一种情况,您的函数将抛出异常。例如,在您的情况下,您可以制作 HttpURLConnection class 的模拟对象,并在您调用 getInputStream() 方法时让他抛出 IOException。
所以你的测试会像
@Test(expected = Exception.class)
public void test() {
HttpURLConnection connectionMock = mock(HttpURLConnection.class);
when(connectionMock.getInputStream()).thenThrow(new IOException());
jiraFunctions.checkJiraStatus(connectionMock);
}
我已经写了异常通过的测试用例,但是没有覆盖代码覆盖。
请帮帮我,我试了很多方法都没有解决。
public String checkJiraStatus(HttpURLConnection httpURLConnection) throws IOException {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
}
in.close();
JSONObject jsonObject = new JSONObject(String.valueOf(stringBuilder));
JSONObject fields = (JSONObject) jsonObject.get("fields");
JSONObject status = (JSONObject) fields.get("status");
return (String) status.get("name");
}catch (IOException |JSONException ioException) {
throw new IOException("Problem while fetching the data"+ioException.getMessage());
}
}
测试用例正确通过但没有给出代码覆盖率。
@Test(expected = Exception.class)
public void testIoException() throws Exception {
when(mockJiraFunctions.checkJiraStatus(any())).thenThrow(new
IOException("Problem while fetching the data"));
jiraFunctions.checkJiraStatus(any());
}
正如我在评论中提到的,您应该 运行 您的真实方法才能获得报道。 并且您应该创建一种情况,您的函数将抛出异常。例如,在您的情况下,您可以制作 HttpURLConnection class 的模拟对象,并在您调用 getInputStream() 方法时让他抛出 IOException。
所以你的测试会像
@Test(expected = Exception.class)
public void test() {
HttpURLConnection connectionMock = mock(HttpURLConnection.class);
when(connectionMock.getInputStream()).thenThrow(new IOException());
jiraFunctions.checkJiraStatus(connectionMock);
}