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

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

我正在为服务器开发 GRPC 客户端。 在 GRPC repo 中,建议以这种方式模拟服务:

     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

我想知道,如果我只是替换会有什么变化

mock(GreeterGrpc.GreeterImplBase.class, delegatesTo(

匿名 class 创建如下:

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

我看不到 Mockito 可以在这里提供任何好处,因为所有调用都委托给委托人。

它是正确的还是我遗漏了什么?

您将无法使用 Mockito 验证您的服务是否以某种特定方式与之交互。例如。您在 HelloWorldClientTest 中看到的“verify(serviceImpl)”调用将不起作用。