Unit testing method that invokes FileWriter

六眼飞鱼酱① 提交于 2019-12-24 01:05:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!