5

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:

Code:

 @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:

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?

1 Answer 1

8

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() {...} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.