簡體   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