我正在为在目录中创建文件的方法编写测试。我的 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 的单元测试方法 https://stackoverflow.com/questions/11878716/unit-testing-method-that-invokes-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();
}
}
我无法修改此方法,因为其他开发人员创建了它。我刚刚被指示为测试自动化创建单元测试。谢谢。