Spock不执行when子句

时间:2016-07-28 01:55:34

标签: grails groovy spock

我的一个spock测试是跳过when子句并向右移动到then子句。

@Unroll
void "test refresh metadata with #consumerNames"() {
    setup:
    consumerNames.each {
        new CredentialConsumer(name: it).save(validate: false)
    }

    when:
    service.refreshMetadata()

    then:
    consumerNames.each { consumerName ->
        Metadata metadata = new Metadata(content: "Metadata for $consumerName")
        ConsumerDefinition consumerDefinition = new ConsumerDefinition(name: consumerName, metadata: metadata)
        1 * mockApplicationLibraryService.fetchConsumerDefinition(consumerName) >> consumerDefinition
        assert CredentialConsumer.findByName(consumerName)?.metadata?.content == metadata.content
    }

    where:
    consumerNames     | _
    ["bacon"]         | _
    ["bacon", "eggs"] | _

}

我得到以下结果......

Condition not satisfied:

CredentialConsumer.findByName(consumerName)?.metadata?.content == metadata.content
                   |          |              |         |       |  |        |
                   |          bacon          null      null    |  |        Metadata for bacon
                   |                                           |  com.datapriviasoftware.completesso.configuration.Metadata@487cd177
                   |                                           false
                   com.datapriviasoftware.completesso.CredentialConsumer : 1

Expected :Metadata for bacon

Actual   :null

当我使用调试器逐步执行它时,它会执行setup子句,跳过when子句,并立即执行then子句。

1 个答案:

答案 0 :(得分:0)

所以,我知道Spock在执行then子句之前使用AST转换来处理when子句中的模拟。当我仔细思考时,我意识到在then子句中处理模拟需要执行整个each循环,因此我需要将显式断言与模拟定义分开。

这有效......

@Unroll
void "test refresh metadata with #consumerNames"() {
    setup:
    consumerNames.each {
        new CredentialConsumer(name: it).save(validate: false)
    }

    when:
    service.refreshMetadata()

    then:
    consumerNames.each { consumerName ->
        Metadata metadata = new Metadata(content: "Metadata for $consumerName")
        ConsumerDefinition consumerDefinition = new ConsumerDefinition(name: consumerName, metadata: metadata)
        1 * mockApplicationLibraryService.fetchConsumerDefinition(consumerName) >> consumerDefinition
    }

    and:
    consumerNames.each { consumerName ->
        assert CredentialConsumer.findByName(consumerName)?.metadata?.content == "Metadata for $consumerName"
    }

    where:
    consumerNames     | _
    ["bacon"]         | _
    ["bacon", "eggs"] | _

}