调用FileWriter的单元测试方法 [英] Unit testing method that invokes FileWriter

查看:246
本文介绍了调用FileWriter的单元测试方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为调用FileWriter的方法编写一个单元测试。我正在使用JUnit 4.8,Powermock和Mockito。我正在测试的方法看起来像这样。

  public void methodToTest(String fileName,String text){

File file = new File(someStaticString )// string是类的静态字段,路径是一个目录

if(!file.exist()){//创建目录}

try {
FileWriter fw = new FileWrite(file.getAbsolutePath()+/fileName,true);
fw.write(text);
fw.close();

catch(Exception e){
e.printStackTrace
}
}

如果file和fileWriter是在方法之外声明的,我可以用mockito和powermock来嘲笑它们,这样我就可以测试可能发生的情况,因为我正在练习BDD 。但是,我不能修改我测试的代码,因为其他开发人员创建它们(尽管我认为开发人员有责任创建单元测试)。

我想知道如何可能)模拟对象下的文件和fw的方法。如果在if()或loop()下创建对象,那么该怎么办?如果我在想什么是不可能的,你可以建议什么样的建议来测试这种方法?我还了解了JUnit的TemporaryFolder。我可以用这个代替文件来创建文件夹和文件吗?



谢谢。

解决方案

您可以将文件名更改为 user.name .test文件,并读取文件,并在完成后删除它。

能够改变静态路径将是更有用的,但如果这是问题,你可以使用../../../../../../../tmp/user.name.file作为文件名并有效地忽略静态路径。 ;)

顺便说一句: catch(Exception e)是一个非常糟糕的主意。你最好删除它恕我直言。


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.

解决方案

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.

这篇关于调用FileWriter的单元测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆