在我的测试课中,我使用了 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 文件,就像我提供的代码中的测试一样,当我在类中运行所有测试时,只有第一个成功。我的猜测是,在第一个测试结束后,临时文件夹消失了,其他测试失败,IOException 说系统找不到给定的路径。问题是如何在不删除文件夹的情况下将同一个文件夹用于多个单元测试,或者这是不可能的,我必须为每个测试用例创建一个临时文件夹?
最佳答案
我假设您尝试使用 org.junit.rules.TemporaryFolder
。
如果您想为所有非静态测试方法保留相同的测试文件夹,您可以使用:
@ClassRule
public static TemporaryFolder outputFolder = new TemporaryFolder();
仅供引用 - 以下语法将在每个 @Test 方法之前创建一个新文件夹,并在每次方法执行后进行清理。
@Rule
public TemporaryFolder outputFolder = new TemporaryFolder();
关于java - 对多个单元测试使用相同的 junit 临时文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761073/