Skip to content

Make GrpcServerRule more reusable #4171

@ensonic

Description

@ensonic

See #2160 for some context. All the linked examples assume one mocks the service that is tested, which sounds weird to me (see https://github.com/grpc/grpc-java/blob/master/examples/src/test/java/io/grpc/examples/helloworld/HelloWorldClientTest.java)
My grpc service talks to other grpc services and I'd like to mock out those. My Dagger module injects those secondary grpc service stubs and hence in the Test dagger module I'll need to provide mocked stubs and this is when things seem to fall apart.

I understand the suggestion to mock the impl instead (again see #2160), but I am not sure how to actually make this work. I have this code:

@Module
public class XyzTestModule {
    protected static final AbcGrpc.AbcImplBase abcImpl =
      mock(AbcGrpc.AbcImplBase.class, delegatesTo(new AbcGrpc.AbcImplBase() {}));

  @Provides
  BindableService provideXzyGrpcService(Datastore datastore) {
    GrpcServerRule grpcServerRule = new GrpcServerRule().directExecutor();
    // FIXME: need to somehow invoke before(), but this is a hack
    try {
      Method before = grpcServerRule.getClass().getDeclaredMethod("before");
      before.setAccessible(true);
      before.invoke(grpcServerRule);
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
      e.printStackTrace();
    }
    grpcServerRule.getServiceRegistry().addService(abcImpl);
    AbcGrpc.AbcBlockingStub abcClient =  AbcGrpc.newBlockingStub(grpcServerRule.getChannel());

    return new XyzService(datastore, abcClient);
  }
}

bur of course the use of reflection is a terrible hack. It looks like I'll have to replicate most of what is in https://github.com/grpc/grpc-java/blob/master/testing/src/main/java/io/grpc/testing/GrpcServerRule.java, right? So maybe the code in GrpcServerRule can be made more resuable. E.g. Datastore has a LocalDatastoreHelper, where I can start()/stop() in my tests @BeforeClass/@afterclass helpers.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions