简体   繁体   English

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

[英]Spock spy - spy class that used in function (Java)

How can I spy for the Class File in anthoer function in class? 如何在班上的其他函数中监视班级文件?
Works for the test when I use new File in the test but not in my class. 当我在测试中使用新文件而不是在课堂上使用该文件时,该测试适用于该测试。

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:
    ...
    ...
}

From official spock docs about Spy : 来自有关Spy的官方Spock文档:

Think twice before using this feature. 使用此功能之前请三思。 It might be better to change the design of the code under specification. 在规范下更改代码的设计可能会更好。

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

And there are no reason to use spy object in test like that. 并且没有理由像这样在测试中使用间谍对象。 If you don't like to redesign code, you can always use groovy metaprogramming: 如果您不想重新设计代码,则可以始终使用groovy元编程:

File.metaClass.exists = {true}

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

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