“尚未创建文件夹";在testclass中使用JUnit临时文件夹时出错 [英] "folder has not yet been created" error when using JUnit temporary folder in testclass

查看:102
本文介绍了“尚未创建文件夹";在testclass中使用JUnit临时文件夹时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误消息尚未创建临时文件夹",该错误来自TemporaryFolder.getRoot()方法抛出的IllegalStateException.看起来它尚未初始化,但是我的研究表明,在setUp()方法中初始化temp文件夹时,通常是这种情况.但是在我看来,将它与@Rule一起使用应该可以工作.有什么想法吗?

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?

测试类

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);
  }
}

推荐答案

您正在使用不支持规则的JUnit 3测试.为此,您必须使用JUnit 4测试.因此

You're using JUnit 3 tests which don't support Rules. You have to use a JUnit 4 test for this. Therefore

  • 从类定义中删除extends TestCase.
  • 删除构造函数,setUp和tearDown方法.
  • @Test批注添加到所有测试方法(以test开头的公共方法.)
  • 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();

来自testWriterAndReader.

有关迁移的更多详细信息:

For more details about the migration: Best way to automagically migrate tests from JUnit 3 to JUnit 4?

这篇关于“尚未创建文件夹";在testclass中使用JUnit临时文件夹时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆