Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clean database tables after each integration test when using Spring Boot and Liquibase?

I have a side project were I'm using Spring Boot, Liquibase and Postgres.

I have the following sequence of tests:

test1();
test2();
test3();
test4();

In those four tests I'm creating the same entity. As I'm not removing the records from the table after each test case, I'm getting the following exception: org.springframework.dao.DataIntegrityViolationException

I want to solve this problem with the following constraints:

  1. I don't want to use the @repository to clean the database.
  2. I don't want to kill the database and create it on each test case because I'm using TestContainers and doing that would increase the time it takes to complete the tests.

In short: How can I remove the records from one or more tables after each test case without 1) using the @repository of each entity and 2) killing and starting the database container on each test case?

like image 323
Julian Avatar asked Jul 13 '20 06:07

Julian


2 Answers

The simplest way I found to do this was the following:

  1. Inject a JdbcTemplate instance
@Autowired
private JdbcTemplate jdbcTemplate;
  1. Use the class JdbcTestUtils to delete the records from the tables you need to.
JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
  1. Call this line in the method annotated with @After or @AfterEach in your test class:
@AfterEach
void tearDown() throws DatabaseException {
    JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1", "table2", "table3");
}

I found this approach in this blog post: Easy Integration Testing With Testcontainers

like image 108
Julian Avatar answered Nov 14 '22 21:11

Julian


Annotate your test class with @DataJpaTest. From the documentation:

By default, tests annotated with @DataJpaTest are transactional and roll back at the end of each test. They also use an embedded in-memory database (replacing any explicit or usually auto-configured DataSource).

For example using Junit4:

@RunWith(SpringRunner.class)
@DataJpaTest
public class MyTest { 
//...
}

Using Junit5:

@DataJpaTest
public class MyTest { 
//...
}
like image 32
Marc Avatar answered Nov 14 '22 23:11

Marc