Skip to main content

Test

This extension integrates @SpringBootTest for better testing experience.

Dependencies

testImplementation("io.github.danielliu1123:grpc-starter-test")

Usage

@InProcessName

After adding the dependency, the gRPC server will use in-process by default.

Get the in-process name using the @InProcessName annotation:

@SpringBootTest
class FooTest {

@InProcessName
String inProcessName;
}

@LocalGrpcPort

Specify the server port type using the grpc.test.server.port-type configuration, the value can be:

  • IN_PROCESS: using in-process. The in-process name can be obtained using the @InProcessName annotation. This is the default value.
  • RANDOM_PORT: Use a random port. The port number can be obtained using the @LocalGrpcPort annotation.
  • DEFINED_PORT: Use the defined port, which is the value of grpc.server.port.

Get random port using the @LocalGrpcPort annotation:

@SpringBootTest(properties = "grpc.test.server.port-type=RANDOM_PORT")
class FooTest {

@LocalGrpcPort
int port;
}

Example

@SpringBootTest(classes = InProcessNameIT.Cfg.class)
class InProcessNameIT {

@InProcessName
String name;

@Test
void testInProcessName() {
var stub = StubUtil.createStub(name, SimpleServiceGrpc.SimpleServiceBlockingStub.class);
var responseMessage = stub.unaryRpc(SimpleRequest.newBuilder().setRequestMessage("World!").build())
.getResponseMessage();

assertThat(responseMessage).isEqualTo("Hello World!");
}

@Configuration(proxyBeanMethods = false)
@EnableAutoConfiguration
static class Cfg extends SimpleServiceGrpc.SimpleServiceImplBase {
@Override
public void unaryRpc(SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
responseObserver.onNext(SimpleResponse.newBuilder()
.setResponseMessage("Hello " + request.getRequestMessage())
.build());
responseObserver.onCompleted();
}
}
}

Configurations

If you want to disable the test extension, use the following configuration:

grpc:
test:
enabled: false