[英]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。
就我而言,我必须使用SpringBean
使用此导入注释SpringBean
字段;
import org.spockframework.spring.SpringBean
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.