Reputation: 175
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.
Upvotes: 6
Views: 18194
Reputation: 26454
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.
Upvotes: 7
Reputation: 748
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));
}
Upvotes: 5