1

我还在学习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 吗?

4

2 回答 2

2

相反,如果您使用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());

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

于 2013-10-30T10:13:40.107 回答
0

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

@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-10-30T10:23:06.550 回答