gpt4 book ai didi

java - jUnit 代码覆盖率中遗漏了 8 个分支中的 6 个

转载 作者:行者123 更新时间:2023-12-02 11:38:27 25 4
gpt4 key购买 nike

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

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());

}

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

最佳答案

您正在谈论线路覆盖或分支覆盖。几乎所有静态分析工具(如声纳等)都会跟踪两者。

如果您谈论的是行覆盖率,我认为A 行已被覆盖。为了检查这一点,IDE 中有各种可用的插件,如 Eclipse、IntelliJ、Netbeans 等。

在 IntelliJ 中,您可以使用“运行覆盖率”选项来运行测试,并且您可以在 IDE 中看到覆盖率。

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

对于gradle,您需要将其添加到build.gradle文件中

gradle test

对于maven,你可以使用

mvn test

关于java - jUnit 代码覆盖率中遗漏了 8 个分支中的 6 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48749895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com