@ExperimentalApi(value="https://github.com/grpc/grpc-java/issues/2488") @NotThreadSafe public final class GrpcCleanupRule extends org.junit.rules.ExternalResource
ExternalResource
that can register gRPC resources and manages its automatic
release at the end of the test. If any of the resources registered to the rule can not be
successfully released, the test will fail.
Example usage:
@Rule public final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
...
// The Channel and Server can be created in any order
grpcCleanup.register(
InProcessServerBuilder.forName("my-test-case")
.directExecutor()
.addService(serviceImpl)
.build()
.start());
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName("my-test-case")
.directExecutor()
.build());
To use as a replacement for GrpcServerRule
:
String serverName = InProcessServerBuilder.generateName();
MutableHandlerRegistry serviceRegistry = new MutableHandlerRegistry();
Server server = grpcCleanup.register(
InProcessServerBuilder.forName(serverName)
.fallbackHandlerRegistry(serviceRegistry)
.build()
.start());
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName(serverName).build());
Constructor and Description |
---|
GrpcCleanupRule() |
Modifier and Type | Method and Description |
---|---|
protected void |
after()
Releases all the registered resources.
|
org.junit.runners.model.Statement |
apply(org.junit.runners.model.Statement base,
org.junit.runner.Description description) |
<T extends ManagedChannel> |
register(T channel)
Registers the given channel to the rule.
|
<T extends Server> |
register(T server)
Registers the given server to the rule.
|
GrpcCleanupRule |
setTimeout(long timeout,
TimeUnit timeUnit)
Sets a positive total time limit for the automatic resource cleanup.
|
public GrpcCleanupRule setTimeout(long timeout, TimeUnit timeUnit)
Note that the resource cleanup duration may or may not be counted as part of the JUnit
Timeout
rule's test duration, depending on which rule is
applied first.
public <T extends ManagedChannel> T register(@Nonnull T channel)
This method need be properly synchronized if used in multiple threads. This method must not be used during the test teardown.
public <T extends Server> T register(@Nonnull T server)
This method need be properly synchronized if used in multiple threads. This method must not be used during the test teardown.
public org.junit.runners.model.Statement apply(org.junit.runners.model.Statement base, org.junit.runner.Description description)
apply
in interface org.junit.rules.TestRule
apply
in class org.junit.rules.ExternalResource
protected void after()
after
in class org.junit.rules.ExternalResource