Spock:模拟类的方法不匹配

时间:2018-11-12 18:09:39

标签: groovy spock

我能够对我的代码的精简版进行通过测试(感谢cgrim!Spock: method not recognized as an invocation),但是使用真实代码,除非getAssetIdBatch返回某些内容,否则该代码将无法工作那不是空的。我不知道为什么我的交互没有实现。在下面,您可以看到三种尝试使getAssetIdBatch返回map1示例的方法。

这是代码的精简版:

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)
        FilterSet filterSet = new FilterSet()
        filterSet.tag = [:]
        filterSet.tag['tag.Location'] = 'Boston'
        filterSet.tag['tag.Color'] = 'red'
        Map<String, String> expectedTags = ['tag.Location':'Boston', 'tag.Color':'red']
        ObjectMapper mapper = new ObjectMapper()
        export.filters = mapper.writeValueAsString(filterSet)

        def assetServiceClient = Mock(AssetServiceClientImpl) {
            Map map1 = [assetIds:["1","2","3","4","5"],scrollId:null]
            getAssetIdBatch(_ as String,_ as String, null, _ as Map) >> map1
            getAssetIdBatch('000', '000', null, ['tag.Location':'Boston', 'tag.Color':'red']) >> map1
            getAssetIdBatch(_, _, _, _) >> map1
        }

        VmExportTaskSplitter splitter = new VmExportTaskSplitter()
        splitter.assetServiceClient = assetServiceClient

        when:
        splitter.splitAndSend(export)

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

运行此命令后,可以看到该批次仍被打印为null。设置交互功能有什么问题?

Using logging directory: './logs'
Using log file prefix: ''
test
batch: null

1 个答案:

答案 0 :(得分:2)

您-像以前一样,遇到了Spock的一个巨大陷阱:combination of Mocking and Stubbing和事实它必须成行出现。形成文档:

  

同一方法调用的模拟和存根必须在同一交互中发生。

您在assetServiceClient.getAssetIdBatch块中插入了map1以返回given,然后在then块中验证了模拟调用。后者隐式指示该模拟返回null而不是map1。想想

1 * assetServiceClient.getAssetIdBatch(_ as String, _ as String, _, _ as Map) // >> null

将该行更改为

1 * assetServiceClient.getAssetIdBatch(_ as String, _ as String, _, _ as Map) >> map1

并在方法的范围内定义map1,它将按预期工作。

您可能还希望从given块中删除重复项。

不用担心,它位于then块中。在进入when块之前,Spock执行所有模拟和存根。如果您希望看到它,请单步执行代码。