问题
I'm trying to write a unit test for a method that calls a 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 file and fileWriter are declared outside the method, I can mock them using mockito and powermock so I can test the possible scenarios that may happen if the method was called since I'm practicing BDD. However, I cannot modify the codes I am testing since other developers created them (Though I think it's the developers responsibility to create unit test).
I wondering how (if it's possible) to mock objects under a method like file and fw. How about if there are objects created under if() or loop()? Can they be mocked as well?
If what I'm thinking is not possible, what recommendation can you suggest to test this kind of methods? I also learned about JUnit's TemporaryFolder. Can I use this in place of file to create Folders and file?
Thanks.
回答1:
You can change the filename to something like "user.name
.test-file" and read the file and delete it when you have finished.
Being able to change the static path would be more useful but if this is problem you can use "../../../../../../../tmp/user.name.file" as a file name and effectively ignore the static path. ;)
BTW: The catch(Exception e)
is a very bad idea. You are better off deleting it IMHO.
回答2:
I think that it is incorrect to mock some object that was created inside method body and will be dereferenced after method completion. I think that it is good practice to test interface that is implemented but not the implementation details itself. In your case you can mock someStaticString
and it seems much better to me than mocking File
or FileWriter
.
来源:https://stackoverflow.com/questions/11878716/unit-testing-method-that-invokes-filewriter