问题
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