Search code examples
testingquarkus

Recommended way to reset in memory H2 database for each QuarkusTest


I'm implementing some BDD @QuarkusTests using RestAssured and an in-memory H2 database. I'm looking for the simplest and recommended way to reset the in memory database (either drop-recreate or delete all entities everywhere) after each test.

I'd like to avoid any hands on ways like create custom DELETE scripts that run manually after each test of table truncates. Is there a clean and quarkus-native way to do this?

EDIT: Please do not recommend anything related to Flyway or other 3rd party dependency.

EDIT 2: I did a quick initial hack by dropping all entities manually but I'm looking for something simpler and automatic

  @AfterEach
  void tearDown() {
    try (final EntityManager em = emf.createEntityManager()) {
      em.getTransaction().begin();
      em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
      em.getTransaction().commit();
      for (EntityType<?> entity : em.getMetamodel().getEntities()) {
        em.getTransaction().begin();
        final Class<?> managedType = entity.getBindableJavaType();
        em.createQuery("FROM " + managedType.getSimpleName(), managedType).getResultList().forEach(em::remove);
        em.getTransaction().commit();
      }
      em.getTransaction().begin();
      em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
      em.getTransaction().commit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

Solution

  • Until a different and better answer is provided we'll go with the hack:

      @AfterEach
      void tearDown() {
        try (final EntityManager em = emf.createEntityManager()) {
          em.getTransaction().begin();
          em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
          em.getTransaction().commit();
          for (EntityType<?> entity : em.getMetamodel().getEntities()) {
            em.getTransaction().begin();
            final Class<?> managedType = entity.getBindableJavaType();
            em.createQuery("FROM " + managedType.getSimpleName(), managedType).getResultList().forEach(em::remove);
            em.getTransaction().commit();
          }
          em.getTransaction().begin();
          em.createNativeQuery("SET REFERENTIAL_INTEGRITY FALSE").executeUpdate();
          em.getTransaction().commit();
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }