单元测试中未涵盖的 catch 块 [英] catch block not covered in unit testing

查看:69
本文介绍了单元测试中未涵盖的 catch 块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个测试用例,用于异常通过但不包括代码覆盖率.

I have written a test case for the exception is passed but does not cover code coverage.

请帮帮我,我试了很多方法都没有解决.

Please help me I tried many ways but doesn't resolve.

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 case passes correctly but didn't give code coverage.

@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 类的模拟对象,并在您对其调用 getInputStream() 方法时让他抛出 IOException.

As I mentioned in comment, you should run your real method to have a coverage. And you should make a situation, where your function will throw an exception. For example in your case you can make a mock object of HttpURLConnection class and make him throw IOException when you call getInputStream() method on it.

所以你的测试会像

@Test(expected = Exception.class)
public void test() {
    HttpURLConnection connectionMock = mock(HttpURLConnection.class);
    when(connectionMock.getInputStream()).thenThrow(new IOException());
    jiraFunctions.checkJiraStatus(connectionMock);
}

这篇关于单元测试中未涵盖的 catch 块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆