我正在尝试为一个使用Google Vision API 和
我已经检查过我的类中使用的对象是否真的是模拟对象,而它确实是。我尝试使用Spock版本1.2-groovy-2.5和1.3-groovy-2.5进行了测试。
被测试的类:
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异常。
_
,但结果仍然相同。即使完全省略存根,结果仍然相同:调用实际方法,抛出NPE异常。 - Roman Abendroth