Writing Integration Tests for Java gRPC Services with an In-Memory Server
gRPC is a strong fit for Java backends that need fast, typed communication between services. Protocol Buffers provide an explicit contract, generated stubs remove much of the boilerplate, and HTTP/2 supports efficient communication between distributed components. These benefits are useful in systems running across Australian regions, such as a Sydney-facing API calling services hosted in Melbourne or Brisbane.
A unit test can verify a service method in isolation, but it cannot prove that the generated protobuf classes, gRPC bindings, status codes, interceptors and client stubs work together. An integration test fills that gap. With InProcessServerBuilder, the server and client communicate inside the same JVM without opening a TCP port.
An in-memory gRPC test is quicker and more deterministic than starting a real network server. It also avoids port allocation problems in parallel builds and removes dependencies on Docker, Kubernetes or a local service registry. This makes it suitable for Maven or Gradle pipelines, including builds running on shared CI agents.
The approach still tests a meaningful part of the application boundary. A test client uses the same generated blocking, future or asynchronous stub that production code uses, while the service is registered with a genuine gRPC server. The result is a compact test that exercises the RPC contract rather than calling an implementation method directly.
| Testing approach | What it verifies | Speed | Typical use |
|---|---|---|---|
| Direct unit test | Service logic with mocked collaborators | Very fast | Validation and branching rules |
| In-process gRPC test | Generated contract, server registration, stub calls and RPC status | Fast | Service-level integration coverage |
| Local network test | gRPC over an actual port and transport stack | Moderate | Configuration and deployment checks |
| Environment test | Service interaction across deployed components | Slow | Release and system verification |
Add The Right Test Dependencies
The test needs the gRPC in-process transport in addition to the normal gRPC server and stub dependencies. With Maven, versions should normally be managed through the gRPC BOM so that grpc-core, grpc-stub, grpc-protobuf and the transport libraries remain compatible.
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-inprocess</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
The exact dependency set varies with the gRPC version and build plugin. Generated code may also require javax.annotation-api or jakarta.annotation-api, depending on the Java and code-generation setup. Keep those choices consistent with the production module rather than adding test-only versions that mask a compile problem.
For Gradle, the equivalent test configuration is usually testImplementation("io.grpc:grpc-inprocess:<version>") and testImplementation("io.grpc:grpc-testing:<version>"). A Java 17 or Java 21 build is common in current Australian teams, but the test design is the same on supported LTS releases.
Build A Named In-Process Server
An in-process server uses a logical name instead of a host and port. The name must be unique for the test, especially when JUnit executes classes concurrently. A UUID is safe, although a stable name can work when every test reliably shuts down its resources.
private String serverName;
private Server server;
private ManagedChannel channel;
private OrderServiceGrpc.OrderServiceBlockingStub client;
@BeforeEach
void setUp() throws Exception {
serverName = InProcessServerBuilder.generateName();
server = InProcessServerBuilder
.forName(serverName)
.directExecutor()
.addService(new OrderService(orderRepository))
.build()
.start();
channel = InProcessChannelBuilder
.forName(serverName)
.directExecutor()
.build();
client = OrderServiceGrpc.newBlockingStub(channel);
}
directExecutor() runs callbacks on the calling thread and removes thread scheduling from a small integration test. That makes failures easier to reproduce and often reduces runtime. It should not be treated as a performance simulation: production may use different executors, event loops and transport behaviour.
The server must register the actual generated service base implementation, such as OrderServiceGrpc.OrderServiceImplBase. If the implementation has dependencies, provide test doubles or lightweight fakes through its constructor. This preserves the service boundary while keeping the test independent of a real database, message broker or external HTTP provider.
Shut Down Every Resource Reliably
A gRPC server and channel own resources that must be released after each test. Relying on the JVM to clean them up can leave non-daemon threads running, create flaky builds and interfere with later tests. JUnit 5's @AfterEach is a suitable place for orderly shutdown.
@AfterEach
void tearDown() throws Exception {
if (channel != null) {
channel.shutdownNow();
channel.awaitTermination(5, TimeUnit.SECONDS);
}
if (server != null) {
server.shutdownNow();
server.awaitTermination(5, TimeUnit.SECONDS);
}
}
Shutdown order is worth keeping consistent. Closing the channel first prevents new client calls, then stopping the server releases the service resources. If a test deliberately exercises cancellation or a deadline, use a bounded wait and record useful diagnostics when termination does not complete.
A shared server can reduce setup time, but it usually makes tests less isolated. Mutable state, mock expectations and service caches can leak between methods. Per-test lifecycle management is generally the safer default for backend integration tests, including suites executed in parallel on CI infrastructure in Sydney or Perth.
Call The Service Through Its Generated Stub
The important distinction between an integration test and a direct unit test is the client call. Construct a protobuf request and invoke the generated stub rather than calling OrderService.getOrder() on the implementation object.
@Test
void returnsAnExistingOrder() {
GetOrderRequest request = GetOrderRequest.newBuilder()
.setOrderId("order-123")
.build();
GetOrderResponse response = client.getOrder(request);
assertThat(response.getOrder().getId()).isEqualTo("order-123");
assertThat(response.getOrder().getStatus())
.isEqualTo(OrderStatus.CONFIRMED);
}
This verifies the protobuf request and response types, method binding, service registration and normal response delivery. It also gives failures a useful contract-level meaning: the RPC did not behave as a client would observe it.
Use assertThrows(StatusRuntimeException.class, ...) for expected gRPC errors, then inspect the status code rather than relying on a message string.
StatusRuntimeException error = assertThrows(
StatusRuntimeException.class,
() -> client.getOrder(missingRequest));
assertThat(error.getStatus().getCode())
.isEqualTo(Status.Code.NOT_FOUND);
A missing resource should produce NOT_FOUND, invalid input should usually produce INVALID_ARGUMENT, and an unauthenticated request should produce UNAUTHENTICATED. Testing these mappings prevents implementation exceptions from escaping as vague UNKNOWN failures.
Keep External Collaborators Controlled
In-memory transport does not make every dependency in-memory. The service can still write to a repository, publish an event or call another API. Integration tests should control those collaborators so that a failure represents the gRPC service contract rather than a temporary dependency problem.
For a repository, an in-memory implementation is often preferable when the test needs realistic state transitions. A Mockito mock is appropriate when the scenario needs precise verification, such as confirming that a cancellation event is published once. Avoid mocking the generated gRPC stub in the test under discussion; that would remove the boundary the test is intended to exercise.
@Test
void cancelsAnOrderAndPublishesAnEvent() {
CancelOrderRequest request = CancelOrderRequest.newBuilder()
.setOrderId("order-123")
.build();
CancelOrderResponse response = client.cancelOrder(request);
assertThat(response.getAccepted()).isTrue();
verify(eventPublisher).publishOrderCancelled("order-123");
}
If the service uses asynchronous work, wait on a clear signal rather than adding an arbitrary sleep. Awaitility, a test latch or a controllable executor can make eventual assertions deterministic. This matters for Australian services processing events across time zones, where an unreliable delay can hide race conditions in CI.
Test Deadlines Metadata And Interceptors
A successful response is only one part of gRPC behaviour. Production clients often attach deadlines, authentication metadata, correlation IDs and tracing headers. Interceptors can be installed on the in-process server or channel to verify those concerns without using a network socket.
A deadline test can arrange for a fake dependency to block, then call the stub with a short deadline:
assertThrows(StatusRuntimeException.class, () ->
client.withDeadlineAfter(50, TimeUnit.MILLISECONDS)
.getOrder(request));
The service should respond with DEADLINE_EXCEEDED or stop its work according to the application’s cancellation policy. Tests must avoid excessively small deadlines because scheduling noise can make a valid implementation fail on a busy build agent.
For metadata, attach a ClientInterceptor or use MetadataUtils.attachHeaders and assert that the server-side interceptor receives the expected header. A correlation ID such as x-request-id is especially useful when logs from services in Brisbane, Adelaide and other locations are combined in a central observability platform.
Keep authentication tests separate from business scenarios. One test should establish that valid credentials reach the service; another should verify that missing or invalid credentials are rejected. This separation makes failures easier to diagnose and avoids creating a large fixture that tests unrelated behaviour.
Cover Streaming And Asynchronous Calls
Unary RPCs are the simplest case, but gRPC also supports server streaming, client streaming and bidirectional streaming. In-process transport supports these patterns, allowing the same test strategy to cover subscription feeds, bulk uploads and event-style interactions.
For a server-streaming method, use a blocking iterator when the generated API provides one:
Iterator<OrderEvent> events = client.streamOrderEvents(request);
assertThat(events.next().getType())
.isEqualTo(OrderEventType.CREATED);
assertThat(events.next().getType())
.isEqualTo(OrderEventType.DISPATCHED);
The service should define how the stream ends and how errors are reported. Tests should cover normal completion, an empty stream, cancellation and a failure after one or more messages. Avoid collecting an unbounded stream into a list because a broken producer can cause the test itself to hang.
Future and asynchronous stubs need a different assertion style. Attach a listener to the returned future and coordinate with a bounded latch, or use a library that converts the result into a test-friendly stage. Always include a timeout so a missing callback produces a failure rather than a permanently blocked build.
Streaming tests are useful for systems that send live operational data to customers, including logistics or utility platforms serving the large distances between Australian cities. They expose backpressure and cancellation mistakes that a unary request test cannot detect.
Make The Suite Fast And Trustworthy
An in-process gRPC test should focus on the service boundary, not reproduce an entire production environment. Use a small fixture, explicit test data and one business behaviour per test. Separate contract checks from repository integration, full network transport and end-to-end deployment tests.
Run the suite with the same generated protobuf sources used by the application. A test that manually constructs an alternate message or bypasses the generated stub can pass while the actual client contract is broken. Include the gRPC tests in the normal Maven or Gradle verification phase so they run locally and in continuous delivery.
Teams working with Australian payment, health or government data may also need tests for redaction and access controls. Never place real customer records into fixtures; use synthetic identifiers and Australian-style examples that cannot be mistaken for production data. Time-sensitive assertions should use an injected clock rather than assuming AEST, daylight-saving changes or a particular deployment region.
The practical next step is to create one JUnit 5 test class for a unary RPC, start an InProcessServerBuilder in @BeforeEach, call the generated blocking stub, and shut down both channel and server in @AfterEach.