【问题标题】:Best way to mock filewriter模拟文件编写器的最佳方法
【发布时间】:2012-08-16 18:45:40
【问题描述】:

我想测试以下方法,特别是调用了 write 和 close 方法(在 write 检查的情况下,所写的是我所期望的)。真正的源代码是 Java,我正在用 Groovy 编写测试。我不能使用地图强制,因为没有默认构造函数。我尝试了 mockFor 和 metaClass,但只有当我将源代码更改为 groovy 并在 groovy 中进行单元测试时,我才能让它们工作。我有任何常规选项来测试此代码吗?下面的代码是 groovy,但 java 方法源非常相似。生成一个真正的header,执行一些日期逻辑,然后写入结果。

class TestWriter {
    protected void writeResultToXMLFile(String response,FileWriter fw, Date today){
        String header = "header";
        try{
            fw.write(header);
            fw.close();
        } catch (IOException ioe){
            String errorMessage = "Unable to write to file";
            try{
                fw.close();
            }catch (IOException ioException){
                errorMessage += ", Error attempting to close the file";
            }
        }
    }
}

【问题讨论】:

    标签: unit-testing groovy metaprogramming


    【解决方案1】:

    另一种可能性是使用像 Mockito 这样的框架来模拟 FileWriter,然后 verify 传递正确的值。

    看起来像这样:

    // create the mock
    FileWriter mock = mock(FileWriter.class);
    
    // call the method under test and pass in the mock 
    
    // verify the intended behaviour
    verify(mock).write("the expected text");
    verify(mock).close();
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      将您的代码类 FileWriter 替换为 Writer 接口,然后您将能够为编写器创建一个模拟实现并测试它是否接收到所有需要的调用

      【讨论】:

      • 我选择了这个答案,因为我正在寻找一个不需要像 Mockito 这样的外部库的解决方案(如果可能的话)。通过遵循这个建议,我能够对 Writer 使用映射强制并编写单元测试。
      猜你喜欢
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 2021-09-08
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      相关资源
      最近更新 更多