Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java TemporaryFolder getRoot() exception

Tags:

java

junit

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?

like image 596
Niru Avatar asked Apr 03 '14 17:04

Niru


1 Answers

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() {...}
like image 100
Niru Avatar answered Nov 05 '22 02:11

Niru