Search code examples
spring-bootjunitgrpc-javacucumber-junit

Call external stub from grpc test class


I am trying to call the grpc service using stub (proto are present in the different jar file). But when I am trying to call that service I am getting caused by io.grpc.statusruntimeexception unimplemented method not found. The same is working fine in main class but not in test case.

DeviceGroupServiceImplBase deviceService = Mockito.mock(DeviceGroupServiceImplBase.class, AdditionalAnswers.delegatesTo(new DeviceGroupServiceImplBase() { }));

public void createInProcessServerAndChannel() throws IOException {
    // Generate a unique in-process server name.
    String serverName = InProcessServerBuilder.generateName();

    // Create a server, add service, start, and register for automatic graceful
    // shutdown.
    grpcCleanup.register(
            InProcessServerBuilder.forName(serverName).directExecutor().addService(deviceService).build().start());

    // Create a client channel and register for automatic graceful shutdown.
    ManagedChannel channel = grpcCleanup
            .register(InProcessChannelBuilder.forName(serverName).directExecutor().build());

    // Create a DeviceGroupServiceClient using the in-process channel;
    groupStub = DeviceGroupServiceGrpc.newBlockingStub(channel);
}

// Test case code
When("user calls getDevice with valid deviceUUID {string}", (String deviceUUID) -> {
    DeviceUuid request = DeviceUuid.newBuilder().setDeviceUuid(deviceUUID).build();
    DeviceGroup groupData = groupStub.getDeviceGroupByDeviceUuid(request);
});

Solution

  • you need to implement getDeviceGroupByDeviceUuid, by default it returns unimplemented status. you can verify if it is calling ServerCall#asyncUnimplementedUnaryCall.

    DeviceGroupServiceImplBase deviceService = 
      Mockito.mock(
        DeviceGroupServiceImplBase.class, 
        AdditionalAnswers.delegatesTo(
          new DeviceGroupServiceImplBase() {
            @Override
            public void getDeviceGroupByDeviceUuid(
                DeviceUuid request, StreamObserver<DeviceGroup> responseObserver) {
              // TODO: implement
            } 
          }));