我编写了一个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());
}有任何建议,如何覆盖该Line A的所有可能的方式,以获得100%的覆盖面?任何帮助都将是伟大的,我也想得到一个解释,所以在未来,我将能够解决这个问题,我自己。
发布于 2018-02-12 18:15:27
您正在讨论的是线路覆盖或分支覆盖。几乎所有的静态分析工具,如声纳等,都会同时进行跟踪。
如果你说的是线路覆盖,我认为的A行已经被覆盖了。为了验证这一点,在中有各种各样的插件可用,比如Eclipse.IntelliJ、Netbeans等等。
在IntelliJ中,您可以使用选项“”运行测试,并且可以看到IDE中的覆盖率。
您也可以在maven和gradle中使用构建任务,
对于gradle,需要将其添加到build.gradle文件中
gradle test对于maven,您可以使用
mvn testhttps://stackoverflow.com/questions/48749895
复制相似问题