Using a gRPC client in Lagom tests

When your Lagom Service exposes a gRPC interface you will need a gRPC Client on your tests. play-grpc provides extensions to Lagom’s testkitLagom’s testkit.

First you have to include the dependency to the testkit extension:

Scala
"com.lightbend.play" %% "lagom-scaladsl-grpc-testkit" % "0.9.1"
Java
"com.lightbend.play" %% "lagom-javadsl-grpc-testkit" % "0.9.1"

Unmanaged client

You can use an unmanaged client with an idiom similar to Lagom’s server.clientserver.client. The main difference is that the gRPC unmanaged client requires manual resource cleanup so you are responsible for invoking close once you are done using the client instance. This option is convenient if you want to reuse the client in multiple tests or even within the same test.

Scala
val grpcClient: GreeterServiceClient = AkkaGrpcClientHelpers.grpcClient(
  server,
  GreeterServiceClient.apply,
)

protected override def afterAll(): Unit = {
  grpcClient.close()
  server.stop()
}

  "say hello over gRPC (unmnanaged client)" in {
    grpcClient
      .sayHello(HelloRequest("Alice"))
      .map {
        _.message should be("Hi Alice! (gRPC)")
      }
  }
Java
GreeterServiceClient client =
    AkkaGrpcClientHelpers.grpcClient(server, GreeterServiceClient::create);
try {
  HelloReply reply =
      client
          .sayHello(HelloRequest.newBuilder().setName("Steve").build())
          .toCompletableFuture()
          .get(5, SECONDS);
  assertEquals("Hi Steve (gRPC)", reply.getMessage());
} finally {
  client.close().toCompletableFuture().get(5, SECONDS);
}

Managed client

The Lagom gRPC managed client is a similar API but will handle the resource management for you. This option is convenient if you want a fresh new isntance of the client on each use, but is also more costly:

Scala
"say hello over gRPC (managed client)" in {
  AkkaGrpcClientHelpers.withGrpcClient(server, GreeterServiceClient.apply _) { grpcClient =>
    grpcClient
      .sayHello(HelloRequest("Alice"))
      .map {
        _.message should be("Hi Alice! (gRPC)")
      }
  }
}
Java
AkkaGrpcClientHelpers.withGrpcClient(
    server,
    GreeterServiceClient::create,
    serviceClient -> {
      HelloReply reply =
          serviceClient
              .sayHello(HelloRequest.newBuilder().setName("Steve").build())
              .toCompletableFuture()
              .get(5, SECONDS);
      assertEquals("Hi Steve (gRPC)", reply.getMessage());
    });
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.