使用JUnit 4中TemporaryFolder規則來管理你的文件系統交互。
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!
}
}
輸出:文本執行
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
後,規則執行,只要文件被使用規則創建處理所有清理, 。
根據你的問題,你也許可以在@Before塊設置你的系統屬性,然後相信他們是本作的主動測試的情況下。
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());
}
}
再次,控制檯輸出:
C:\Users\Jeremiah\AppData\Local\Temp\junit7380201043103411996\Cancel.txt
true
C:\Users\Jeremiah\AppData\Local\Temp\junit7380201043103411996\Cancel_temp.txt
true
爲什麼不建立在你的系統默認的臨時目錄下的臨時文件? ['Files.createTempFile'](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#createTempFile-java.nio.file.Path-java.lang。字符串java.lang.String中-java.nio.file.attribute.FileAttribute ...-)。使用JUnit,你也可以使用['TemporaryFolder'](http://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html) – Tunaki
配置文件爲servlet提供了一個路徑,想要執行文件操作。所以servlet本身正在寫和刪除這些文件。我確實試圖給它一個臨時目錄的路徑,但刪除仍然沒有完成 –
該servlet只能通過ServletConfig來獲得配置。如果你這樣做,那麼你可以在你的測試中調用'Servlet.init(ServletConfig)'方法並指定一個測試配置。 –