代码之家  ›  专栏  ›  技术社区  ›  Anirudh Jadhav

代码覆盖率jUnit中缺少8个分支中的6个

  •  0
  • Anirudh Jadhav  · 技术社区  · 8 年前

    我编写了一个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%的覆盖率?任何帮助都将是巨大的,我也想得到一个解释,所以在未来我将能够自己解决这个问题。

    1 回复  |  直到 8 年前
        1
  •  1
  •   lrathod    8 年前

    您所说的是线路覆盖率或分支覆盖率。几乎所有静态分析工具(如声纳等)都会跟踪这两种情况。

    如果你说的是线路覆盖率,我想 A线已覆盖。 要检查这一点,IDE中有各种插件,如Eclipse、IntelliJ、Netbeans等。

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

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

    对于gradle,您需要在内部版本中添加此项。gradle文件

    gradle test
    

    对于maven,您可以使用

    mvn test