Groovy Spock 文件测试

Groovy Spock File test

我即将开始学习 spock,我正在尝试一些基本的东西。 我想检查文件的:exist() 和 getText() 功能 所以我写了下面的测试:

class MyTestSpec extends Specification {
  def "test file"() {
    given:
       def mockFile = Mock(File,constructorArgs :["./doesNotExist.txt"])
       mockFile.exists() >>  true
       mockFile.getText() >> "sampleText"

    when:
       def res = ""
       if(mockFile.exists()) {
          res = mockFile.getText()
       }

    then:
       "sampleText" == res
        1 * mockFile.exists()
        1 * mockFile.getText()
    }
}

失败于:

Too few invocations for:

1 * mockFile.getText()   (0 invocations)

Unmatched invocations (ordered by similarity):

None

当我在 'then' 块中评论 'verifications' 时,我得到:

java.lang.NullPointerException at java.io.FileInputStream.(FileInputStream.java:138) at groovy.util.CharsetToolkit.(CharsetToolkit.java:69) at MyTestSpec.Test Existing Resource(MyTestSpec.groovy:83)

所以我的问题是:我究竟应该如何组织我的考试?为什么它假定不应调用 getText?

我正在使用 groovy 2.4 和 spock 1.0

解决方案是:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib:3.1') 
@Grab('org.ow2.asm:asm-all:5.0.3') 

import spock.lang.*

class MyTestSpec extends Specification {
  def "test file"() {
    given:
       def mockFile = GroovyMock(File, constructorArgs :["./doesNotExist.txt"])

    when:
       def res = ""
       if(mockFile.exists()) {
          res = mockFile.getText()
       }

    then:
       "sampleText" == res
        1 * mockFile.exists() >> true
        1 * mockFile.getText() >> "sampleText"
    }
}

其中一个问题是创建模拟。由于 groovy 某些功能的动态特性 - 例如getText() method for File class - is added at runtime. It requires mocks to be constructed in a different way. Have a look at spock mock implementation enum 并提取:

An implementation specifically targeting Groovy callers. Supports mocking of dynamic methods, constructors, static methods, and "magic" mocking of all objects of a particular type.

第二个问题是定义模拟行为和验证交互。当你模拟和存根时,它必须在同一个交互中发生(这里,在 then 块中),here 是文档的相关部分。