繁体   English   中英

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

[英]Spock spy - spy class that used in function (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:
    ...
    ...
}

来自有关Spy的官方Spock文档:

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

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

并且没有理由像这样在测试中使用间谍对象。 如果您不想重新设计代码,则可以始终使用groovy元编程:

File.metaClass.exists = {true}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM