【问题标题】:spock - mock static method is not workingspock - 模拟静态方法不起作用
【发布时间】:2016-08-20 09:47:55
【问题描述】:

我正在尝试使用 groovy 的 metaClass 约定来模拟静态方法 readAttributes 之一,但真正的方法会被调用。

这就是我模拟静态函数的方式:

def "test"() {
    File file = fold.newFile('file.txt')
    Files.metaClass.static.readAttributes = { path, cls ->
        null
    }

    when:
        fileUtil.fileCreationTime(file)
    then:
        1 * fileUtil.LOG.debug('null attribute')
}

我在这里做错了吗?

我的java方法

public Object fileCreationTime(File file) {
    try {
        BasicFileAttributes attributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
        if(attributes == null) {
            LOG.debug("null attribute");
        }  
        //doSomething
    } catch (IOException exception) {
        //doSomething
    }
    return new Object();
}

【问题讨论】:

    标签: java unit-testing groovy spock


    【解决方案1】:

    您可以为此使用 GroovySpy,如 spock documentation 中所述

    在你的情况下,它会是:

    def filesClass = GroovySpy(Files, global: true)
    filesClass.readAttributes(*_) >> null
    

    【讨论】:

    【解决方案2】:

    我使用一级间接解决了这个问题。我创建了test class 的一个实例方法,它就像这个静态调用的包装器。

    public BasicFileAttributes readAttrs(File file) throws IOException {
        return Files.readAttributes(file.toPath(), BasicFileAttributes.class);
    }
    

    从测试中我模拟了实例方法。

    FileUtil util = Spy(FileUtil);
    util.readAttrs(file) >> { null }
    

    这解决了我的问题。

    【讨论】:

      【解决方案3】:

      简短的回答是不可能,请看this问题。

      有可能:

      • 被测代码是用 groovy 编写的
      • mocked(修改过的)类必须用 groovy 代码实例化。

      解决方法是提取将属性返回到另一个类的逻辑,而不是直接使用Files

      【讨论】:

      • @Suganthan 您是否按原样复制了我提供的示例? Cloaure 的 args 也很重要。
      • 是的,我也这样做了,中间断言没有问题,但方法仍然被调用
      • @Suganthan 能否请您提供一个可运行的示例?没有它,可能很难提供帮助。
      • @Suganthan,如果您觉得我的回答有用,请接受并点赞。
      • @Suganthan,可能是。但是在常规中 private 根本不是 private ;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多