I'm trying to use org.junit.rules.TemporaryFolder in one of my junit to test File I/O. I've initialized it like this:
@Rule
public TemporaryFolder temporaryFolder;
@Before
public void setup() {
this.temporaryFolder = new TemporaryFolder();
}
@After
public void tearDown() {}
@Test
public void testCsvDataFile() throws IOException {
File testCsvFile = this.temporaryFolder.newFile("text.csv");
FileWriter csvFileWriter = new FileWriter(testCsvFile);
BufferedWriter bufferedWriter = new BufferedWriter(csvFileWriter);
bufferedWriter.write("col1,col2,col3\n");
bufferedWriter.write("1,test1,val1\n");
bufferedWriter.write("2,test2,val2\n");
bufferedWriter.close();
Map<Long,Data> data = MyReader.readCSV(testCsvFile);
assertTrue(2 == data.size());
}
However, I get an exception:
java.lang.IllegalStateException: the temporary folder has not yet been created
at org.junit.rules.TemporaryFolder.getRoot(TemporaryFolder.java:127)
at org.junit.rules.TemporaryFolder.newFile(TemporaryFolder.java:64)
When I look at the TemporaryFolder code, it uses an internal attribute folder in the function getRoot() that is never set. The constructor sets a different field: parentFolder.
There is a create() method that sets the folder variable but its marked to be for test purposes only.
I am using JDK 1.7. Am I constructing the TemporaryFolder incorrectly? Is there anything else, a system property that needs to be set for this?
The constructor cannot be called in setup(), and it has to be:
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void setup() {...}
@After
public void tearDown() {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With