"folder has not yet been created" 在测试类中使用 JUnit 临时文件夹时出错

"folder has not yet been created" error when using JUnit temporary folder in testclass

我收到错误 "the temporary folder has not yet been created",它来自 TemporaryFolder.getRoot() 方法抛出的 IllegalStateException。看起来它没有初始化,但我的研究表明,当临时文件夹在 setUp() 方法中初始化时,通常会出现这种情况。但是在我看来,像我一样将它与 @Rule 一起使用应该可行。有什么想法吗?

测试class

public class FileReaderTest extends TestCase {

  @Rule
  public TemporaryFolder folder = new TemporaryFolder();

  public FileReaderTest(String testName) {
    super(testName);
  }

  @Override
  protected void setUp() throws Exception {
    super.setUp();
  }

  @Override
  protected void tearDown() throws Exception {
    super.tearDown();
  }

  public void testCSVWriterAndReader() throws Exception{
    testWriterAndReader(new CSVFileWriter(), new CSVFileReader());
  }

  private void testWriterAndReader(FileWriteService writer, FileReader reader) throws Exception {
    folder = new TemporaryFolder();
    File tempFile = folder.newFile("test.csv");
    DataSet initializedData = createMockData();
    writer.writeDataSetToFile(initializedData, tempFile.getPath());
    DataSet readData = reader.getDataFromFile(new FileInputStream(tempFile));
    assertEquals(initializedData, readData);
  }
}

您正在使用不支持规则的 JUnit 3 测试。您必须为此使用 JUnit 4 测试。因此

  • 从 class 定义中删除 extends TestCase
  • 删除构造函数、setUp 和 tearDown 方法。
  • 为所有测试方法添加 @Test 注释(Public 以 test 开头的方法。)

应该进行迁移。之后你必须删除行

folder = new TemporaryFolder();

来自 testWriterAndReader

有关迁移的更多详细信息:Best way to automagically migrate tests from JUnit 3 to JUnit 4?