本文介绍了Java TemporaryFolder getRoot()异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的一个junit中使用org.junit.rules.TemporaryFolder来测试文件I/O.我已经这样初始化了:

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)

当我查看TemporaryFolder代码时,它使用了从未设置的函数getRoot()中的内部属性文件夹.构造函数设置一个不同的字段:parentFolder.

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.

有一个create()方法可设置文件夹变量,但将其标记为仅用于测试目的.

There is a create() method that sets the folder variable but its marked to be for test purposes only.

我正在使用JDK 1.7.我是否错误地构造了TemporaryFolder?还有什么需要为此设置的系统属性吗?

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?

推荐答案

构造函数不能在setup()中调用,它必须是:

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() {...}

这篇关于Java TemporaryFolder getRoot()异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 12:23