代码覆盖中错过了8个分支中的6个jUnit

时间:2018-02-12 15:29:10

标签: java junit

我编写了一个java方法来读取文件,并将文件内容作为成功运行的字符串返回。然后我将文件位置作为输入传递,并以String格式返回文件内容。以下是代码段:

public String readFile(String url) throws <Custom Exception>
    {
        StringBuilder stringBuilder = new StringBuilder("");
        try (BufferedReader br = new BufferedReader(new
            FileReader(url))) //Line A
        {
            String line;
            while ((line = br.readLine()) != null)
            {
                stringBuilder.append(line);
            }
        }
        catch (IOException e)
        {
            throw new <Custom Exception>;
        }
        return stringBuilder.toString();
    }

我还需要为以下代码片段编写jUnit。我尽力覆盖Line A,但遗憾的是我无法获得100%的代码覆盖率。由于一些限制,我无法更改代码,但可以更改jUnit,我写了下面的jUnit,这给了我60%的代码覆盖率。

FileServiceImpl fileServiceImpl = new FileServiceImpl();

    @Test
    public void readFile_should_read_file() throws <custom_exception>
    {
        String expected = "Test data";
        File file = new File("test.txt");
        try
        {
            file.createNewFile();
            FileWriter writer = new FileWriter(file);
            writer.write("Test data");
            writer.close();
        }
        catch (IOException e)
        {
            return;
        }

        String actual = fileServiceImpl.readFile(file.getAbsolutePath());
        file.delete();
        assertEquals(expected, actual);

    }

    @Test(expected = <custom_exception>.class)
    public void readFile_should_throw_<custom_exception>() throws <custom_exception>
    {

        File file = new File("test.txt");

        fileServiceImpl.readFile(file.getAbsolutePath());

    }

有任何建议如何以所有可能的方式覆盖Line A以获得100%的覆盖率?任何帮助都会很棒,我也希望得到一个解释,以便将来我能够自己解决这个问题。

1 个答案:

答案 0 :(得分:0)

您正在谈论线路覆盖范围或分支机构覆盖范围。几乎所有静态分析工具,如声纳等,都跟踪两者。

如果您正在讨论线路覆盖,我认为线路A已被覆盖。要检查这一点,IDE中有各种插件,如Eclipse,IntelliJ,Netbeans等。

在IntelliJ中,您可以使用“run with coverage”选项运行测试,您可以在IDE中查看覆盖范围。

您还可以在maven和gradle中使用构建任务,

对于gradle,您需要在build.gradle文件中添加它

gradle test

对于maven,你可以使用

mvn test