【发布时间】:2019-12-20 05:56:24
【问题描述】:
如果我按照这两个测试运行,我会得到错误。
第一次测试
@Rule
public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
@Test
public void findAll() throws Exception {
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder
.forName(serverName)
.directExecutor()
.addService(new Data(mockMongoDatabase))
.build()
.start());
// Create a client channel and register for automatic graceful shutdown.
RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub(
grpcCleanup.register(InProcessChannelBuilder
.forName(serverName)
.directExecutor()
.build()));
RoleOuter.Response response = stub.findAll(Empty.getDefaultInstance());
assertNotNull(response);
}
第二次测试
@Test
public void testFindAll() {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081)
.usePlaintext()
.build();
RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub(channel);
RoleOuter.Response response = stub.findAll(Empty.newBuilder().build());
assertNotNull(response);
}
io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference cleanQueue SEVERE: ~~~ Channel ManagedChannelImpl{logId=1, target=localhost:8081} 没有正确关闭!!! ~~~ 确保调用 shutdown()/shutdownNow() 并等待 awaitTermination() 返回 true。
java.lang.RuntimeException: ManagedChannel 分配站点 在 io.grpc.internal.ManagedChannelOrphanWrapper$ManagedChannelReference.(ManagedChannelOrphanWrapper.java:94)
如果我注释掉其中一个,则没有错误,单元测试虽然通过,但如果两者一起运行,则会引发异常。
编辑
根据建议。
@Test
public void testFindAll() {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8081)
.usePlaintext()
.build();
RoleServiceGrpc.RoleServiceBlockingStub stub = RoleServiceGrpc.newBlockingStub(channel);
RoleOuter.Response response = stub.findAll(Empty.newBuilder().build());
assertNotNull(response);
channel.shutdown();
}
【问题讨论】:
-
grpcCleanup是什么?您应该使用InProcessServerBuilder(检查)创建一个服务器,然后在同一个链式调用中添加相应的服务。 -
已编辑,
@Rule public GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();,我是新手,使用示例 -
我会尝试在
@Before中创建所有这些东西,然后在@After中停止服务器;无论如何,您正在测试的那些方法不应该负责启动和停止 gRPC 服务器。 -
使用 GrpcCleanupRule,您不需要
@After、@Before获取 grpc 资源。但第二次测试需要注册它创建的通道。清理规则将调用正常关闭。 -
第二个测试是在它自己的文件中的某种集成测试(与第一个测试不同的 .java 文件),您能否提供有关如何正确编写这种集成测试的代码。