gRPC unit test stub
What's inside this article
⌄
- GRPC test stub for unit and integration testing
- GRPC unit test stub
Let’s imagine we have a gRPC service YourServiceImpl.java:
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 YourTest.java:
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 YourTest.java:
Server server = ServerBuilder
.forPort(9999)
.addService(testStubService)
.build();
server.start();
server.awaitTermination();