繁体   English   中英

Groovy Spock 模拟调用模拟类的真实方法

[英]Groovy Spock mock calling real method of mocked class

我正在尝试为使用 Google 的视觉 API 和来自google-cloud-vision库的AnnotatorImageClient的类编写单元测试。 问题是我模拟的AnnotatorImageClient由于某种原因仍然调用真正的batchAnnotateImages方法,然后抛出一个 NPE,这破坏了我的测试。 我以前从未在模拟中看到过这种行为,我想知道我是否做错了什么,spock/groovy 中是否存在错误,或者它是否与那个 Google 库有关?

我已经检查过我的类中使用的对象是否真的是一个模拟,它是。 我已经尝试过 Spock 版本 1.2-groovy-2.5 和 1.3-groovy.2.5

被测试的类:

public class VisionClient {

    private final ImageAnnotatorClient client;

    @Autowired
    public VisionClient(final ImageAnnotatorClient client) {
        this.client = client;
    }

    public Optional<BatchAnnotateImagesResponse> getLabelsForImage(final Image image) {
        var feature = Feature.newBuilder().setType(LABEL_DETECTION).build();

        var request = AnnotateImageRequest.newBuilder()
                .addFeatures(feature)
                .setImage(image)
                .build();

        return Optional.ofNullable(client.batchAnnotateImages(singletonList(request)));
}

考试:

class VisionClientSpec extends Specification {
    def "The client should use Google's client to call Vision API"() {
        given:
        def googleClientMock = Mock(ImageAnnotatorClient)
        def visionClient = new VisionClient(googleClientMock)
        def imageMock = Image.newBuilder().build()

        when:
        def resultOpt = visionClient.getLabelsForImage(imageMock)

        then:
        1 * googleClientMock.batchAnnotateImages(_ as List) >> null
        !resultOpt.isPresent()
    }
}

我希望模拟简单地返回null (我知道这个测试没有多大意义)。 相反,它调用com.google.cloud.vision.v1.ImageAnnotatorClient.batchAnnotateImages这会引发 NPE。

ImageAnnotatorClient是用 Java 编写的,方法batchAnnotateImages(List<AnnotateImageRequest> requests)final

Spock 能够模拟 Java final 类,但在模拟 Java final 方法方面表现不佳。

你可以使用PowerMock来获得你需要的东西, 这里是如何让它与 Spock 一起工作的教程。

就我而言,我必须使用SpringBean使用此导入注释SpringBean字段;

import org.spockframework.spring.SpringBean

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM