I am writing a test for a method that creates a file in a directory. This is what my JUnit test looks like:
@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 my problem destroyFile.delete(); //why is this returning false? destroyDir.delete(); //will also return false since file was not deleted above }
I managed to delete the file using deleteOnExit (), but I cannot delete the directory using delete or deleteOnExit. I will also run other tests for other scripts in this test script, so I don't want to use deleteOnExit.
I do not know why I cannot delete it in the JUnit test script until I can delete the file created and modified by FileWriter at runtime when the code is not a JUnit test. I also tried to execute the endless method after the testing method and delete the file manually, but it tells me that another program is still using the file, although I can change its contents.
Hopefully someone can suggest a way to delete files and directories created during the tests. Thanks: D
For clarity, the test method I looks like this: The single test method that calls FileWriter
Edit: Here is a validation method
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(); } }
I cannot change this method as other developers have created it. I was simply assigned to create unit tests to automate testing. Thanks.
source share