我正在编写一个测试方法,用于在目录中创建文件。以下是我的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();
}
}
我无法修改这个方法,因为它是由其他开发人员创建的。我的任务只是按照指示为测试自动化创建单元测试。谢谢。
objectUnderTest.createFile(nameOfFile, textToWrite);
释放了所有资源,即关闭了任何相关的流/写入器吗? - A4L