如何将http请求回滚到将数据保存到db的api端点

问题描述

所以我正在编写一些组件测试,据我所知,测试本身不应该直接访问db或对应用程序一无所知。

Http调用很容易模拟,但是实现中的数据库访问又如何模拟呢?

所以我所做的是我向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));
    }

解决方法

好吧,这不是交易,因此无法回滚,但是我可以创建另一个API,在测试完成后将删除此数据