Search code examples
javajunitmockitogrpc

How to test and mock a GRPC service written in Java using Mockito


The protobuf definition is as follows:

syntax = "proto3";

package helloworld;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

I need to use Mockito along with JUnit testing.


Solution

  • The idea is to stub the response and stream observer.

    @Test
    public void shouldTestGreeterService() throws Exception {
    
        Greeter service = new Greeter();
    
        HelloRequest req = HelloRequest.newBuilder()
                .setName("hello")
                .build();
    
        StreamObserver<HelloRequest> observer = mock(StreamObserver.class);
    
        service.sayHello(req, observer);
    
        verify(observer, times(1)).onCompleted();
    
        ArgumentCaptor<HelloReply> captor = ArgumentCaptor.forClass(HelloReply.class);
    
        verify(observer, times(1)).onNext(captor.capture());
    
        HelloReply response = captor.getValue();
    
        assertThat(response.getStatus(), is(true));
    }