Spock spy - 在函数(Java)中使用的间谍类



如何在类中监视类中的类文件?
当我在测试中使用新文件但在课堂上使用新文件时,适用于测试。

public class Clazz {
    public void fun(String path) {
        File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException();
        }
    }
}

//Spock-test
class test extends Specification {
    given:
    GroovySpy(File, global: true, useObjenesis: true)
    def mockFile = Mock(File) {
      exists() >> true
    }
    new File(path) >> {mockFile}
    when:
    Clazz.fun("test.file")
    then:
    ...
    ...
}

来自关于间谍的官方史波克文档:

使用此功能之前请三思。改变可能会更好 规范下的代码设计。

http://spockframework.org/spock/docs/1.0/interaction_based_testing.html

并且没有理由在这样的测试中使用间谍对象。如果你不喜欢重新设计代码,你可以随时使用时髦的元编程:

File.metaClass.exists = {true}

最新更新