我正在为在目录中创建文件的方法编写测试。这是我的 JUnit 测试的样子:
@Before
public void setUp(){
objectUnderTest = new ClassUnderTest();
//assign another directory path for testing using powermock
WhiteBox.setInternalState(objectUnderTest, "dirPathField", mockDirPathObject);
nameOfFile = "name.txt";
textToWrite = "some text";
}
@Test
public void shouldCreateAFile(){
//create file and write test
objectUnderTest.createFile(nameOfFile, textToWrite);
/* this method creates the file in mockPathObject and performs
FileWriter.write(text);
FileWriter.close();
*/
File expect = new File(mockPathObject + "\\" + nameOfFile);
assertTrue(expect.exist());
//assert if text is in the file -> it will not be called if first assert fails
}
@After
public void tearDown(){
File destroyFile = new File(mockPathObject + "\\" + nameOfFile);
File destroyDir = new File(mockPathObject);
//here's my problem
destroyFile.delete(); //why is this returning false?
destroyDir.delete(); //will also return false since file was not deleted above
}
我可以使用 deleteOnExit() 删除文件,但无法使用 delete 或 deleteOnExit 删除目录。我还将在此测试脚本中针对其他场景执行其他测试,因此我不想使用 deleteOnExit。
我不知道为什么我不能在 JUnit 测试脚本中删除它,而当代码不是 JUnit 测试时,我可以删除 FileWriter 在运行时创建和修改的文件。我还尝试在测试方法之后执行无限循环并手动删除文件,但它告诉我其他程序仍在使用该文件,尽管我能够修改其内容。
希望有人可以建议一种方法来删除测试期间创建的文件和目录。感谢:D
为了更清楚,我测试的方法看起来像这个调用 FileWriter 的单元测试方法
编辑:这是测试的方法
public void createFile(String fileName, String text){
//SOME_PATH is a static string which is a field of the class
File dir = new File(SOME_PATH); //I modified SOME_PATH using whitebox for testing
if(!dir.exists()){
booelan createDir = dir.mkdirs();
if(!createDir){
sysout("cannot make dir");
return;
}
}
try{
FileWriter fileWrite = new FileWriter(dir.getAbsolutePath() + "/" + fileName, true);
fileWrite.write(text);
fileWrite.close();
}
catch(Exception e){
e.printStackTrace();
}
}
我无法修改此方法,因为其他开发人员创建了它。我只是被指示为测试自动化创建单元测试。谢谢。