Search code examples
jakarta-eejunith2junit5quarkus

How to reset / drop H2 database in Quarkus after each test method to make them independed?


I´m using the H2 database in my Quarkus project with the @QuarkusTestResource annotation. Each test method is doing tests and checks if a certain number of users exist etc.

The problem I´m facing is that the database won´t be resetted after each test run, which is why the test fail as they are getting results of previous test runs.

@QuarkusTestResource(value = H2DatabaseTestResource.class)
class UserServiceTest {


    @Inject
    UserService userService;

    @Inject
    UserRepository userRepository;

    private User userA;
    private User userB;

    @Transactional
    @BeforeEach
    void setUp() {
        userA = new User();
        userA.setEmail("a");
        userA.setName("a");

        userB = new User();
        userB.setName("b");
        userB.setEmail("b");

        userRepository.persist(userA);
        userRepository.persist(userB);
    }

    @Test
    void testA(){
       //count == 2
    }


    @Test
    void testA(){
       //count == 4
    }


}

How do I reset the H2 database after each test to make them independend from each other?


Solution

  • I'm using @TestTransaction instead of @Transaction in each of my tests.

    @QuarkusTest
    public class TestInvoiceRepositoryfindAllInvoicesToBePaid {
    
      @Inject
      MyRepository myRepository;
    
      @Test
      @TestTransaction
      public void do_something_in_database_01() {
        // it generates and persist data I need for my test
        generateTestData();
        // test my repo method to make sure it does what I want
        MyObject myObject = myRepository.findSomething();
        assertNotNull(myObject);
      }
    
      @Test
      @TestTransaction
      public void do_something_in_database_02() {
        // here I need to insert the data again, because
        // the previous test rolled everything back at the end of it
        generateTestData();
        // test my repo method to make sure it does what I want
        myRepository.findSomething2();
      }
    
      private void generateTestData() {
        ...
        ...
        ...
        myRepository.persist(something);
      }
    }