【问题标题】:Junit Test case for file文件的 Junit 测试用例
【发布时间】:2013-10-30 10:04:31
【问题描述】:

我还在学习junit,我想知道如何为这个问题编写一个junit测试用例。我也在使用 emma 插件来运行覆盖范围。将值设置为(字符串)路径和名称后该怎么办?在@Test中

public static void createReport(final String path, final String name) throws IOException {
        File outDir = new File("Out");
        if (!outDir.exists()) {
            if (!outDir.mkdir()) {
            }
        }
}

还需要在设置参数值后使用 assertEquals 吗?

【问题讨论】:

  • 如果您需要建议,您需要展示您的实际方法。这个对参数没有任何作用,也无法说出你想要测试什么。

标签: java junit emma


【解决方案1】:

如果您改为使用outDir.mkdirs()(如果文件夹不存在则创建文件夹),那么 Emma 不会抱怨该行未被测试覆盖。

如果您想非常彻底,您测试代码的方式是在故意丢失目录的情况下运行它并检查它是否已创建。作为测试的一部分删除输出文件夹:

File outDir = new File("Out")

/* You will probably need something more complicated than
 * this (to delete the directory's contents first). I'd
 * suggest using FileUtils.deleteDirectory(dir) from
 * Apache Commons-IO.
 */
outDir.delete();

// Prove that it's not there
assertFalse(outDir.exists());

createReport(...);

// Prove that it has been created
assertTrue(outDir.exists());

或者将报告写入临时文件夹(如果您可以使用该选项)。

【讨论】:

    【解决方案2】:

    我的建议是使用一个临时文件夹,以便在测试后保持干净:

    @Rule
    public TemporaryFolder folder = new TemporaryFolder();
    

    您可以使用该对象来定义一个新的路径文件夹。

    File tmpFolder = folder.newFolder("subfolder");
    File tmpFile = new File(tmpFolder.getAsbolutePath(),"newFileName");
    

    你所要做的就是用这个对象调用你的方法:

    obj.createReport(tmpFolder.getAbsolutePath(), tmpFile.getAsbolutePath() )
    

    然后在你的单元测试中你可以检查目录是否已经创建:

    Assert.asserttrue(tmpFolder.exists());
    Assert.asserttrue(tmpFile.exists());
    

    【讨论】:

      猜你喜欢
      • 2013-04-08
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      相关资源
      最近更新 更多