【发布时间】:2020-04-19 13:04:00
【问题描述】:
我想模拟我的 grpc 客户端,以通过抛出 new StatusRuntimeException(Status.UNAVAILABLE) 来确保它能够抵御故障(这是在将 java.net.ConnectException: Connection refused 抛出到 grpc 客户端时抛出的异常)。但是,生成的类是 final 的,所以 mock 不起作用。
如何让 BlahServiceBlockingStub 抛出 new StatusRuntimeException(Status.UNAVAILABLE) 而无需重构我的代码以围绕 BlahServiceBlockingStub 创建一个包装类?
这是我尝试过的(BlahServiceBlockingStub 是由 grpc 生成的):
@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)
.
.
.
因为我尝试模拟 grpc 生成的最终类:
public static final class BlahServiceBlockingStub extends io.grpc.stub.AbstractStub<BlahServiceBlockingStub> {
private BlahServiceBlockingStub(io.grpc.Channel channel) {
super(channel);
}
【问题讨论】: