java如何将http请求回滚到将数据保存到数据库的api端点
因此,我正在编写一些组件测试,据我所知,测试本身不应该直接访问db或了解有关应用程序的任何信息
Http调用很容易模拟,但是如何在实现中模拟db访问呢
因此,我所做的是向api端点发出http请求,该端点将数据保存到db中,该数据用于测试目的,目标是在测试后回滚该事务
@Before
public void setupTripEvents() throws ExecutionException, InterruptedException {
dbIntegrationMock = new DbIntegrationMock();
setupTrips(1L, "CHARGING_STATUS_CHANGE");
setupTrips(2L, "CHARGING_STATUS_CHANGE");
setupTrips(3L, "DRIVER_LOGIN");
setupTrips(4L, "DRIVER_LOGOUT");
setupTrips(5L, "IGNITION_ON");
setupTrips(6L, "IGNITION_OFF");
}
private void setupTrips(long l, String triggerType) throws ExecutionException, InterruptedException {
TripEventEntity tripEventEntity = new TripEventEntity();
<---- data ---->
dbIntegrationMock.saveTripEventEntity(tripEventEntity);
}
public Void saveTripEventEntity(TripEventEntity tripEventEntity) throws ExecutionException, InterruptedException {
return HttpClient.forService(Service.withName("componentname"))
.send(HttpRequest.forPut("/dev/db/save/tripevententity")
.withPayload(tripEventEntity)
.withHeader(HttpHeaders.ACCEPT, "application/json"),
HttpResponseType.of(Void.class, MediaType.of("application/json")))
.whenComplete(HttpStatusToExceptionMapper::statusToException)
.thenApply(response -> response.payload().orElse(null))
.toCompletableFuture()
.get();
}
@PutMapping(value = "/db/save/tripevententity",
produces = "application/json")
public DeferredResult<ResponseEntity<Void>> saveTripEvent(HttpEntity<TripEventEntity> request) {
log.info("Save trip event entity...");
return process("tripevententity", "", o -> o, request, call -> save(request));
}
# 1 楼答案
好的,这不是一个事务,因此无法回滚,但我可以创建另一个api,在测试完成后删除此数据