Spock:方法未识别为调用

时间:2018-11-12 00:29:15

标签: groovy spock

试图弄清楚为什么Spock似乎没有将(模拟对象的)方法调用识别为调用。查看了文档(http://spockframework.org/spock/docs/1.1-rc-3/all_in_one.html#_mocking),无法弄清楚。

这是代码的精简版:

class VmExportTaskSplitter implements TaskSplitter<Export> {

    @Inject
    AssetServiceClient assetServiceClient

    @Override
    int splitAndSend(Export export) {

        Map batch = [:]
        Map tags = [:]

        if (true) {
            println('test')
            batch = assetServiceClient.getAssetIdBatch(export.containerUuid,
                    export.userUuid, (String) batch.scrollId, tags)
            print('batch: ')
            println(batch)
        }

        return 1

    }
}

现在是测试:

class VmExportTaskSplitterSpecification extends Specification{
    def "tags should be parsed correctly"(){
        setup:
        Export export = new Export(containerUuid: "000", userUuid: "000", chunkSize: 10)
        AssetServiceClient client = Mock(AssetServiceClientImpl)
        VmExportTaskSplitter splitter = new VmExportTaskSplitter()
        splitter.assetServiceClient = client
        Map map1 = [assetIds:["1","2","3","4","5"],scrollId:null]
        client.getAssetIdBatch(_ as String,_ as String, null, _ as Map) >> map1

        when:
        splitter.splitAndSend(export)

        then:
        1 * client.getAssetIdBatch(_ as String, _ as String, _ as String, _ as Map)
    }
}

这是令人讨厌的部分:assetServiceClient.getAssetIdBatch调用两侧的两行都被打印出来。但是Spock声称没有任何调用...

Using logging directory: './logs'
Using log file prefix: ''
test
batch: [assetIds:[1, 2, 3, 4, 5], scrollId:null]

Too few invocations for:

1 * client.getAssetIdBatch(_ as String, _ as String, _ as String, _ as Map)   (0 invocations)

Unmatched invocations (ordered by similarity):

None

1 个答案:

答案 0 :(得分:1)

更改此行:

1 * client.getAssetIdBatch(_ as String, _ as String, _ as String, _ as Map)   (0 invocations)

...打开:

1 * client.getAssetIdBatch(_ as String, _ as String, _, _ as Map)

VmExportTaskSplitter中,您将空Map传递到getAssetIdBatch方法中,因此batch.scrollId将是null,并且将不匹配_ as String。 / p>


您的规范也可以简化,但这取决于您需要测试的内容。从then部分猜测出来,只有在调用getAssetIdBatch方法时才进行测试,这样就足以编写如下代码:

def "tags should be parsed correctly"() {
    setup:
    Export export = new Export(containerUuid: "000", userUuid: "000", chunkSize: 10)
    AssetServiceClient client = Mock(AssetServiceClient)
    VmExportTaskSplitter splitter = new VmExportTaskSplitter()
    splitter.assetServiceClient = client

    when:
    splitter.splitAndSend(export)

    then:
    1 * client.getAssetIdBatch('000', '000', null, [:])
}