对多个单元测试使用相同的 junit 临时文件夹

Use same junit temporary folder for multiple unit tests

在我的测试中 class 我使用 junit 的临时文件夹。然后我在这个文件夹中创建一个新的 pdf 文件,写入这个文件并做出我的断言。我的单元测试看起来像:

@Test
public void testGeneratePdfIntegration1() throws Exception {

    InputStream isMxml = SuperBarcodeProcTest.class.getResourceAsStream(RES_MXML_JOB_1);
    InputStream isThumb = SuperBarcodeProcTest.class.getResourceAsStream(RES_PNG_JOB_1);
    InputStream isPpf = SuperBarcodeProcTest.class.getResourceAsStream(RES_PPF_JOB_1);

    Path destination = tempFolder.newFile("target1.pdf").toPath();

    superBarcodeProc = new SuperBarcodeProc(isThumb, isMxml, isPpf, destination.toString());
    superBarcodeProc.setDescription("Bogen: 18163407_01_B04_ST_135gl_1000_1-1");
    superBarcodeProc.setBarcode("18163407_01");
    superBarcodeProc.generatePdf();

    assertTrue(Files.exists(destination));
    assertTrue(Files.size(destination) > 1024);
}

测试结束后,正在删除临时文件夹。问题是我有多个单元测试,它们在同一个临时文件夹中生成具有不同设置的 pdf 文件,就像我提供的代码中的测试一样,当我 运行 class 中的所有测试只有第一个成功。我的猜测是,在第一个测试结束后,临时文件夹消失了,其他测试失败,IOException 说系统找不到给定的路径。问题是如何在不删除文件夹的情况下将同一个文件夹用于多个单元测试,或者这是不可能的,我必须为每个测试用例创建一个临时文件夹?

我找到了解决方案。我声明我的临时文件夹是静态的,这导致了上述问题。

我假设您尝试使用 org.junit.rules.TemporaryFolder。 如果您想为所有非静态测试方法保留相同的测试文件夹,您可以使用:

@ClassRule
public static TemporaryFolder outputFolder = new TemporaryFolder();

仅供参考 - 以下语法会在每个 @Test 方法之前创建一个新文件夹,并在每个方法执行后进行清理。

@Rule
public TemporaryFolder outputFolder = new TemporaryFolder();