簡體   English   中英

Java 中測試 gRPC ServerInterceptor 的問題

[英]Issues in Testing gRPC ServerInterceptor In Java

我有一個用 java 編寫的 gRPC 攔截器

我的 gRPC 攔截器看起來像這樣

public class GrpcServerInterceptor implements ServerInterceptor {
    @Override
    public <R, T> ServerCall.Listener<R> interceptCall(ServerCall<R, T> call,
                                                                 Metadata requestHeaders, ServerCallHandler<R, T> next) {

        if(call == null || next == null)
            return null;

        if(call != null) {
            String actionName = call.getMethodDescriptor().getBareMethodName();
            String serviceName = call.getMethodDescriptor().getServiceName();
            State.Holder.set(State.newBuilder().withControllerName(serviceName).withActionName(actionName).withFramework("grpc").build());
        }

        ServerCall.Listener<R> delegate = next.startCall(call, requestHeaders);

        return new ForwardingServerCallListener.SimpleForwardingServerCallListener<R>(delegate) {
            @Override
            public void onHalfClose() {
                try {
                    super.onHalfClose();
                } catch (Exception e) {
                    call.close(Status.INTERNAL
                            .withCause (e)
                            .withDescription("error message"), new Metadata());
                }
            }
        };
    }
}

我只想在 junit 中對上述攔截器進行單元測試。

我在構建 ServerCall、Metaddata 和 ServerCallHandler 對象並將它們四處傳遞時遇到問題。

我嘗試在我的單元測試中創建服務器調用 object,如下所示。

      ServerCall serverCall = new ForwardingServerCall() {
        @Override
        protected ServerCall delegate() {
          return null;
        }

        @Override
        public MethodDescriptor getMethodDescriptor() {
          return MethodDescriptor.newBuilder().
              setType(MethodType.UNKNOWN).
              setRequestMarshaller(ProtoUtils.marshaller((StudentRequest.getDefaultInstance()))).
              setResponseMarshaller(ProtoUtils.marshaller(StudentResponse.getDefaultInstance())).
              setFullMethodName(generateFullMethodName("com.test.cloud.sc.grpc.backend.service.StudentServiceImpl", "getStudentInfo")).
              build();
        }
      };

但是上面的代碼塊在設置請求和響應編組器方面存在問題。

我如何使用最少的代碼設置對我的攔截器的所有場景進行單元測試,並且我根本不想啟動 grpc 服務器?

編輯 1

如何改進 gRPC 攔截器中的 null 檢查處理?

非常感謝

看看https://github.com/grpc/grpc-java/blob/master/api/src/test/java/io/grpc/ServerInterceptorsTest.javahttps://github.com/grpc/grpc- java/blob/master/core/src/test/java/io/grpc/util/UtilServerInterceptorsTest.java查看服務器攔截器是如何測試的。

關於null ,grpc 框架不會在callnext中傳遞 null 所以我看不出有任何理由去檢查。 在任何情況下,請考慮使用 Guava 中的com.google.common.base.Preconditions.checkNotNull

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM