在Maven测试/资源目录

时间:2016-07-26 19:54:00

标签: java maven junit

我正在尝试为可以编写和删除文件的java servlet编写一些单元测试。我有我的dev和prod构建的config.properties文件,以及一个只在测试期间调用的test / resources中的文件。我写入一个稍后删除的临时文件。

canceled.filepath = SRC /测试/资源/ Cancel.txt temp.filepath = SRC /测试/资源/ Cancel_temp.txt

我的问题是我从servlet抛出一个错误,说我无法删除临时文件。我认为这是由于权限错误。我可以在任何地方制作这些文件,以便我的单元测试并获得wirte / delete的完全许可吗?

由于

1 个答案:

答案 0 :(得分:2)

使用Junit 4 TemporaryFolder 规则为您管理文件系统互动。

b = raw_input("Do you like video games? y/n")

输出:

public class MyTestClass {
 //MUST be public
    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Test
    public void test() throws Exception{
   //You can create new files.
    File tmpFile = tempFolder.newFile();
    System.out.println(tmpFile.getAbsolutePath());
    System.out.println(tmpFile.exists());

    //Or new Folders
    File myFolder = tempFolder.newFolder("My_Folder");
    System.out.println(myFolder.getAbsolutePath());
    System.out.println(myFolder.exists());

    //or a combination of them.
    File newFileInMyFolder = tempFolder.newFile("My_Folder\\subfile.txt");
    System.out.println(newFileInMyFolder.getAbsolutePath());
    System.out.println(newFileInMyFolder.exists());

    // The Junit rule uses the system property 'java.io.tempdir' to create them, and it handles the cleanup outside
    // the scope of your test!
    }
}
  

文本执行后,Rule实现处理所有清理,   只要文件是使用规则创建的。

根据您的问题,您可以在 @Before 块中设置系统属性,然后相信它们会在活动测试的上下文中出现。

    C:\Users\Jeremiah\AppData\Local\Temp\junit4815976615865849247\junit796088998678325697.tmp
true
C:\Users\Jeremiah\AppData\Local\Temp\junit4815976615865849247\My_Folder
true
C:\Users\Jeremiah\AppData\Local\Temp\junit4815976615865849247\My_Folder\subfile.txt
true

再次,控制台输出:

public class MyServletTest {
    //MUST be public
    @Rule
    public TemporaryFolder tempFolder = new TemporaryFolder();

    @Before
    public void setTestPaths() throws Exception {
        File cancelFile = tempFolder.newFile("Cancel.txt");
        File cancelTemp = tempFolder.newFile("Cancel_temp.txt");

        System.setProperty("canceled.filepath", cancelFile.getAbsolutePath());
        System.setProperty("temp.filepath", cancelTemp.getAbsolutePath());
    }

    @After
    public void restorePaths() {
        //FIXME:  The JVM will be reused, if you have any other tests relying on the system properites they will be getting the values set in the BEFORE block.
    }

    @Test
    public void checkSysVars() {
        String cancelPath = System.getProperty("canceled.filepath");
        String tmpPath = System.getProperty("temp.filepath");

        File cancelFile = new File(cancelPath);
        File cancelTemp = new File(tmpPath);
        System.out.println(cancelFile.getAbsolutePath());
        System.out.println(cancelFile.exists());
        System.out.println(cancelTemp.getAbsolutePath());
        System.out.println(cancelTemp.exists());

    }
}