The grpc-java project provides
GrpcCleanupRule which is a helpful way to clean up
GrpcService resources in JUnit 4 tests, but it doesn't work with JUnit 5. JUnit 5 doesn't support
@Rule classes, but rather has moved that functionality into Extensions. Additionally, the GRPC folks have said they aren't moving to JUnit 5 for a while, and they suggest sticking with JUnit 4.
Here at StackHawk, we want to use JUnit 5 exclusively, and we want the test resources to get automatically cleaned up to avoid test pollution. So we wrote a JUnit 5 Extension called
GrpcCleanupExtension that handles the channel/server resource cleanup after each test invocation.
If you run a JUnit 5 test with the
GrpcCleanupRule, you'll see something this in the logs:
Which means that the
GrpcCleanupRule did not fire (because JUnit 5 doesn't support
@Rule), and the previous server instance was replaced without shutting down correctly.
Grpc Cleanup Extension Use
Here's a look at how our Grpc Services are set up and how we use the cleanup Extension in tests.
Let's say we have a
GrpcService implementation called
IntegrationService that's set up like this:
When we go to write a test for
IntegrationServer, we set up a
GrpcCleanupExtension instance. The syntax is a little non-Kotlinesque because extensions need to be final static member variables (not in a companion object).
And that's it!
How The Cleanup Extension Works
Not surprisingly, the
GrpcCleanupExtension looks very similar to the
GrpcCleanupRule. It keeps track of a list of servers/channels, and shuts them down after each test execution in the
C'est La Fin
In order to avoid JUnit 4 when testing
GrpcService classes, we wrote a
GrpcCleanupExtension. It hooks into the JUnit 5 test lifecycle to clean up server/channel resources. Enjoy!