spock - 模拟静态方法不起作用

Sug*_*lai 7 java groovy unit-testing spock

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

这就是我嘲笑静态函数的方式:

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')
}
Run Code Online (Sandbox Code Playgroud)

我在这里做错了吗?

我的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();
}
Run Code Online (Sandbox Code Playgroud)

Sug*_*lai 7

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

public BasicFileAttributes readAttrs(File file) throws IOException {
    return Files.readAttributes(file.toPath(), BasicFileAttributes.class);
}
Run Code Online (Sandbox Code Playgroud)

从测试中我嘲笑了实例方法。

FileUtil util = Spy(FileUtil);
util.readAttrs(file) >> { null }
Run Code Online (Sandbox Code Playgroud)

这解决了我的问题。


Opa*_*pal 5

简而言之,这是不可能的,请看看这个问题。

如果有以下任一情况,则有可能:

  • 被测试的代码是用groovy编写的
  • 模拟(更改)的类必须在 Groovy 代码中实例化。

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