【发布时间】:2020-02-12 11:03:04
【问题描述】:
过去几天我一直在摸索一个奇怪的问题。我有一个 JPA 存储库,它是现场注入服务类的。在运行服务器并通过客户端发送请求时完美运行,但通过集成测试执行代码时,字段注入类 (CustomerRepository) 始终为空。
我通过互联网尝试了各种建议,但我没有找到与我类似的情况,任何帮助将不胜感激
服务类
@GRpcService
public class CustomerService extends CustomerServiceGrpc.CustomerServiceImplBase {
@Autowired
private CustomerRepository repository;
@Override
public void createCustomer(CreateCustomerRequest request, StreamObserver<CreateCustomerResponse> responseObserver) {
final CustomerDao convertedDao = ProtoToDaoConverter.convertCustomerRequestProtoToCustomerDao(request);
repository.save(convertedDao);
responseObserver.onNext(CreateCustomerResponse.newBuilder().setSuccess(true).build());
responseObserver.onCompleted();
}
}
集成测试
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class CustomerServiceIT {
@Rule
private final GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
@Test
public void something() throws IOException {
String serverName = InProcessServerBuilder.generateName();
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder
.forName(serverName).directExecutor().addService(new CustomerService()).build().start());
customerServiceGrpc.CustomerServiceBlockingStub blockingStub = CustomerServiceGrpc.newBlockingStub(
// Create a client channel and register for automatic graceful shutdown.
grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build()));
final CreateCustomerRequest request = CreateCustomerRequest.newBuilder().setFirstName("Simon").setSecondName("Brown").setRole("Product Developer").build();
final CreateCustomerResponse response = blockingStub.createCustomer(request);
}
}
【问题讨论】:
-
如何在集成测试中配置注入?
-
无外部配置,例如使用@SpringBootTest。
-
然后阅读 Erunafailaro 的回答。测试和运行配置之间必须存在差异,否则它会起作用。
标签: java spring-boot spring-data-jpa grpc-java