Mockito mock(clazz, delegatesTo(..)) vs anonymous class

Viewed 109

I'm working on GRPC client for the server. In GRPC repo the advise is to mock a service in a such manner:

     private final GreeterGrpc.GreeterImplBase serviceImpl =
      mock(GreeterGrpc.GreeterImplBase.class, delegatesTo(
          new GreeterGrpc.GreeterImplBase() {
          // By default the client will receive Status.UNIMPLEMENTED for all RPCs.
          // You might need to implement necessary behaviors for your test here, like this:
          //
          // @Override
          // public void sayHello(HelloRequest request, StreamObserver<HelloReply> respObserver) {
          //   respObserver.onNext(HelloReply.getDefaultInstance());
          //   respObserver.onCompleted();
          // }
          }));

https://github.com/grpc/grpc-java/blob/master/examples/src/test/java/io/grpc/examples/helloworld/HelloWorldClientTest.java

I wonder, what would change if I just replace

mock(GreeterGrpc.GreeterImplBase.class, delegatesTo(

with anonymous class creation like this:

 private final GreeterGrpc.GreeterImplBase serviceImpl =
          new GreeterGrpc.GreeterImplBase() {
          // By default the client will receive Status.UNIMPLEMENTED for all RPCs.
          // You might need to implement necessary behaviors for your test here, like this:
          //
          // @Override
          // public void sayHello(HelloRequest request, StreamObserver<HelloReply> respObserver) {
          //   respObserver.onNext(HelloReply.getDefaultInstance());
          //   respObserver.onCompleted();
          // }
          };

I don't see any benefits Mockito can offer here as all calls are delegated to the delegate.

Is it correct or am I missing something?

1 Answers

You will lose the ability to use Mockito to verify that your service was interacted with in some specific way. E.g. the "verify(serviceImpl)" call you can see in HelloWorldClientTest would not work.

Related