/// Resources / gRPC
gRPC testing in Java via server reflection: a dynamic unary call with no .proto file
The usual way to test a gRPC service in Java is to copy its .proto into the test project, run protoc, and call the generated stub. That ties the test build to the service build and breaks the moment a field is renamed. The server already knows its own schema; it will tell you over the reflection service, which is exactly what grpcurl does. Here is the same trick in about 150 lines of Java, as a Cucumber step.
What the scenario should read like
Scenario: The greeter answers by name
When I call the grpc method "helloworld.Greeter/SayHello" on "localhost:50051" with:
"""
{ "name": "L3git" }
"""
Three things identify a call: the target as host:port, the method as package.Service/Method, and the request as JSON in a doc string. There is no .proto in the repository and no protobuf-maven-plugin in the pom. The feature file is the only place the method name appears.
Step one: ask the server for its descriptors
A server with reflection enabled exposes grpc.reflection.v1alpha.ServerReflection. One request with file_containing_symbol set to the service name returns the FileDescriptorProto that declares it. That file usually imports others (timestamps, wrappers, your own common types), so the client walks the dependency list and fetches each one by file name until nothing is missing:
private Map<String, FileDescriptorProto> reflectFileDescriptors(ManagedChannel channel, String symbol) throws Exception {
ServerReflectionGrpc.ServerReflectionStub stub = ServerReflectionGrpc.newStub(channel);
Map<String, FileDescriptorProto> byName = new HashMap<>();
List<String> pending = new ArrayList<>();
pending.add(symbol);
boolean bySymbol = true; // first round by symbol, then by file name
while (!pending.isEmpty()) {
String query = pending.remove(0);
for (FileDescriptorProto fdp : oneReflection(stub, query, bySymbol)) {
if (byName.containsKey(fdp.getName())) continue;
byName.put(fdp.getName(), fdp);
for (String dep : fdp.getDependencyList()) {
if (!byName.containsKey(dep)) pending.add(dep);
}
}
bySymbol = false;
}
return byName;
}
oneReflection is a bidirectional stream used as a one-shot: send one ServerReflectionRequest, collect the FileDescriptorProto bytes from the response, complete the stream, and give up after 20 seconds so a wrong port fails with a message instead of hanging the suite.
Step two: build the descriptors and the dynamic call
FileDescriptor.buildFrom needs its dependencies already built, so the protos are built recursively, dependencies first. From there the service and method descriptors give you the input and output types, and the rest is DynamicMessage plus a hand-made MethodDescriptor:
Descriptor inputType = method.getInputType();
Descriptor outputType = method.getOutputType();
DynamicMessage.Builder reqBuilder = DynamicMessage.newBuilder(inputType);
JsonFormat.parser().ignoringUnknownFields().merge(jsonRequest == null ? "{}" : jsonRequest, reqBuilder);
DynamicMessage request = reqBuilder.build();
io.grpc.MethodDescriptor<DynamicMessage, DynamicMessage> grpcMethod =
io.grpc.MethodDescriptor.<DynamicMessage, DynamicMessage>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.UNARY)
.setFullMethodName(serviceName + "/" + methodName)
.setRequestMarshaller(ProtoUtils.marshaller(DynamicMessage.getDefaultInstance(inputType)))
.setResponseMarshaller(ProtoUtils.marshaller(DynamicMessage.getDefaultInstance(outputType)))
.build();
DynamicMessage response = ClientCalls.blockingUnaryCall(channel, grpcMethod, CallOptions.DEFAULT, request);
return JsonFormat.printer().includingDefaultValueFields().print(response);
Two details matter. ignoringUnknownFields() means a stray key in the test JSON is dropped rather than failing the parse, which is what you want when the service adds a field before the test does. includingDefaultValueFields() on the printer means a false or 0 in the reply shows up in the JSON instead of being omitted, so a substring assertion on "ok": false actually works.
The step definition
With the client in a support class, the generated step is five lines. The reply is printed to the console (so it is in the Cucumber report) and saved into the API context so a later step can read it:
private final com.example.support.GrpcClient grpc = new com.example.support.GrpcClient();
@When("I call the grpc method {string} on {string} with:")
public void callGrpc(String method, String target, String request) throws Exception {
String grpcResponse = grpc.callJson(target, method, request);
System.out.println("gRPC response: " + grpcResponse);
api.save("grpcResponse", grpcResponse);
org.junit.jupiter.api.Assertions.assertTrue(grpcResponse.contains("L3git"),
"gRPC response did not contain: L3git");
}
The assertTrue line is only emitted when the recorder step has a response contains value. For a field-level check, a custom script step after it can read api.vars.get("grpcResponse") and parse it with the JSON library already on the classpath.
What this does not do
- Only unary calls. The
MethodTypeis hard-coded toUNARY. Server-streaming, client-streaming and bidirectional methods are not supported by this step; the descriptor lookup works for them, the call does not. - Plaintext only. The channel is built with
usePlaintext(). Against a TLS port the reflection request fails with a transport error rather than a useful message. On the publicgrpcb.intest server that is the difference between:9000(works) and:9001(does not). - Reflection must be enabled on the server. In grpc-java that is
ProtoReflectionService.newInstance()added to the server builder; in Go it isreflection.Register(s). Many production deployments switch it off, so run this against a test or staging instance, or turn it on behind a flag. - The method name is exact. It is
package.Service/Methodwith the proto package, not the Java package.Greeter/SayHellowithout the package fails with gRPC service not found via reflection. - Five test-scoped dependencies.
grpc-netty-shaded,grpc-protobuf,grpc-stub,grpc-services(1.68.1) andprotobuf-java-util(3.25.5). The generator injects them into the pom only when a scenario uses a gRPC step, so REST-only projects stay lean.
In L3git this is the gRPC - unary call entry under the non-REST step button in the API tab: target, method, request JSON and an optional response contains. Generate the project and the GrpcClient above is copied into support/ with the dependencies added, then mvn test runs it like any other scenario. The same shape covers WebSocket and Kafka; the setup walkthrough is guide 10 and the protocol list is on the API testing tool page.
Questions
How do I check the method name and request shape without a .proto file?
Use grpcurl against the same target: grpcurl -plaintext host:port list shows the services, and grpcurl -plaintext host:port describe package.Service shows the methods and their message types. Whatever grpcurl can call this client can call, because both use the same reflection service.
Does the request JSON support ${vars} saved by earlier steps?
Not in the shipped step: the doc string is handed to callJson as-is. If you need a value from a previous REST response in the gRPC request, build the JSON in a custom script step that reads api.vars and calls grpc.callJson itself.
Can I test this offline?
Yes. Any gRPC server with reflection on will do, including a 40-line Python one (pip install grpcio grpcio-reflection) or moul/grpcbin in Docker on localhost:9000. Nothing in the client depends on the public internet.