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

I am getting the error "temp folder has not been created yet" which is coming from the IllegalStateException

method TemporaryFolder.getRoot()

. It looks like it's not initialized, but my research showed me that this usually happens when the temp folder is initialized in setUp () -method. But using it with @Rule

like me should work in my opinion. Any ideas?

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

      

+6


source to share


1 answer


You are using JUnit 3 tests that don't support rules. For this you need to use JUnit 4. Therefore

  • Remove extends TestCase

    from class definition.
  • Remove the constructor, setUp method, and tearDown.
  • Add annotation @Test

    to all test methods (public methods that start with a test.)

should do the migration. Subsequently, you must remove the line



folder = new TemporaryFolder();

      

from testWriterAndReader

.

More on migration: Best way to automatically migrate tests from JUnit 3 to JUnit 4?

+3


source







All Articles