简体   繁体   中英

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 !!

The encouraged way to test a service is to use the in-process transport and a normal stub. Then you can communicate with the service like normal, without lots of mocking. Overused mocking produces brittle tests that don't instill confidence in the code being tested.

GrpcServerRule uses in-process transport behind-the-scenes. We now I suggest taking a look at the examples' tests, starting with hello world .

Edit: We now recommend GrpcCleanupRule over GrpcServerRule . You can still reference the hello world example.

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM