如何使用 mockito 来模拟 grpc ServiceBlockingStub 来抛出 StatusRuntimeException(Status.UNAVAILABLE)?
我想模拟我的 grpc 客户端,以确保它通过抛出一个 (这是抛出到 grpc 客户端时引发的异常)来恢复故障。但是,生成的类是最终的,因此 mock 将不起作用。new StatusRuntimeException(Status.UNAVAILABLE)
java.net.ConnectException: Connection refused
如何让 BlahServiceBlockingStub 抛出,而不必重构我的代码来围绕 BlahServiceBlockingStub 创建一个包装类?new StatusRuntimeException(Status.UNAVAILABLE)
这就是我尝试过的(BlahServiceBlockingStub是由gpc生成的):
@Test
public void test() {
BlahServiceBlockingStub blahServiceBlockingStub = mock(BlahServiceBlockingStub.class);
when(blahServiceBlockingStub.blah(any())).thenThrow(new StatusRuntimeException(Status.UNAVAILABLE));
blahServiceBlockingStub.blah(null);
}
不幸的是,我得到了以下异常,如预期:
org.mockito.exceptions.base.MockitoException:
Cannot mock/spy class BlahServiceGrpc$BlahServiceBlockingStub
Mockito cannot mock/spy following:
- final classes
- anonymous classes
- primitive types
at MyTestClass.test(MyTestClass.java:655)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
.
.
.
因为我试图嘲笑gpc生成的最终类:
public static final class BlahServiceBlockingStub extends io.grpc.stub.AbstractStub<BlahServiceBlockingStub> {
private BlahServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}