gRPC test stub for unit and integration testing

Let’s imagine we have a gRPC service:

public class YourServiceImpl extends YourService.YourServiceImplBase {
  @Override 
  public void yourMethod() {
    // This is original realization
  }
}

We are writing a unit test or integration test, and we need to make a test stub for this service. Let’s use Mockito. The code we write below can be used in any way. You can even use it in pure Java. Let’s connect the dependencies to the project:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.23.4</version>
</dependency>
<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
    <version>1.9.3</version>
</dependency>
<dependency>
    <groupId>org.objenesis</groupId>
    <artifactId>objenesis</artifactId>
    <version>2.1</version>
</dependency>

Now, let’s mock our service:

YourService.YourServiceImplBase testStubService = mock(YourService.YourServiceImplBase.class, delegatesTo(
    new YourService.YourServiceImplBase() {
  @Override
  void yourMethod() {
    // This is the realization for the test
  }
}))

It remains to run our test stub:

Server server = ServerBuilder
    .forPort(9999)
    .addService(testStubService)
    .build()
server.start()
server.awaitTermination()
Telegram channel

If you still have any questions, feel free to ask me in the comments under this article or write me at promark33@gmail.com.

If I saved your day, you can support me 🤝

Leave a Reply

Your email address will not be published. Required fields are marked *