Unit testing method that calls FileWriter

I am trying to write unit test for a method that calls FileWriter. I am using JUnit 4.8, Powermock and Mockito. The method I'm testing looks like this.

public void methodToTest(String fileName, String text){ File file = new File (someStaticString) //string is a static field of the class and the path is a dir if(!file.exist()){ //create dir} try{ FileWriter fw = new FileWrite(file.getAbsolutePath() + "/" fileName, true); fw.write(text); fw.close(); } catch(Exception e){ e.printStackTrace } } 

If the file and the Writer file are declared outside the method, I can make fun of them using mockito and powermock so that I can check for possible scripts that might happen if the method has been called since I have been doing BDD. However, I cannot modify the codes that I am testing as other developers have created them (although I believe that the developers are responsible for creating the unit test).

I am wondering how (if possible) to mock objects under such a way as a file and fw. How about if there are objects created in if () or loop ()? Can they taunt?

If what I think is impossible, what recommendation can you offer to test such methods? I also found out about JUnit TemporaryFolder. Can I use this instead of a file to create folders and a file?

Thanks.

+2
source share
2 answers

You can change the file name to something like " user.name .test-file" and read the file and delete it when you're done.

The ability to change the static path would be more useful, but if this is a problem, you can use "../../../../../../../tmp/user.name. File" as the name file and effectively ignore the static path .;)

BTW: catch(Exception e) is a very bad idea. You better remove it IMHO.

+2
source

I think it’s incorrect to mock some object that was created inside the method body and will be dereferenced after the method is completed. I believe that it is good practice to test an interface that is implemented, but not the implementation itself. In your case, you can make fun of someStaticString , and it seems a lot better to me than a File or FileWriter mockery.

+1
source

All Articles