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

只愿长相守 提交于 2021-02-08 13:04:25

问题


I get the error "the temporary folder has not yet been created", which comes from an IllegalStateException thrown by the TemporaryFolder.getRoot() method. It looks like it's not initialized, but my research showed me that this is usually the case when the temp folder is initialized in setUp()-method. But using it with @Rule like I did should work in my opinion. Any ideas?

The test 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);
  }
}

回答1:


You're using JUnit 3 tests which don't support Rules. You have to use a JUnit 4 test for this. Therefore

  • Remove extends TestCase from the class definition.
  • Remove the constructor, the setUp and the tearDown method.
  • Add the @Test annotation to all test methods (Public methods that start with test.)

should do the migration. Afterwards you have to delete the line

folder = new TemporaryFolder();

from testWriterAndReader.

For more details about the migration: Best way to automagically migrate tests from JUnit 3 to JUnit 4?



来源:https://stackoverflow.com/questions/31201904/folder-has-not-yet-been-created-error-when-using-junit-temporary-folder-in-tes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!