javahibernatejpajunitautotest

Cleaning db entities after test


I'm writing an autotest(with java maven+junit+cucumber)

Now I try to make some delete queries to db after the end, but face some problems:

  1. Tables are connected between each other and by the end of the test I have a bunch of rows in the other tables that reference to my initial entity1 and entity2 and need to cascade delete them and that takes a lot of time, eventually it will lead to after method taking more time than test itself
  2. Tables are not specified on cascade delete and I cant change it since it is expected behavior
  3. it is dev environment that is used for manual tests also so I cant just delete all data, I need to delete only what is created by autotest

I know there is some hibernate thing but I have never used it and Im not sure if It can make what I need

Im looking for some options were I can save how db was before test then do test and then revert all what happend to db so it is same as it was before test


Solution

  • There are 3 ways to do that. Probably both are not „the best”, but works.

    1. Hibernate has a feature called initial import, that use import.sql file. You need to recreate database before each test. This solution is ancient, and difficult to maintain in an environment with multiple tests.
    2. You can use a combination of Liquidbase or Flyway and testcontainers. Then each test will start with a separated DB from docker container. Testcontainer will be set up database and liquidbase/flyway will fill it.
    3. Use an old library called DBUnit with some extensions for Junit5.