How to clean database tables or records with springboot and testconatiner after every test?

Viewed 15

I have many integration tests running with Testcontainer and Springboot.

I am getting this error for tests, where I am using the same objects to save in the database.

org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint

There are 7-8 tables eg. table1, table2,... I have tried TURNCATING the table with CASCADE. It does not turncates them.


        val tablesTobeCleared = listOf(
            "TRUNCATE TABLE table1 CASCADE;",
            "TRUNCATE TABLE table2 CASCADE;",
            "TRUNCATE TABLE table3 CASCADE;",
            "TRUNCATE TABLE table4 CASCADE;",
            "TRUNCATE TABLE table5 CASCADE;",
            "TRUNCATE TABLE table6 CASCADE;",
            "TRUNCATE TABLE table7 CASCADE;",
            "TRUNCATE TABLE table8 CASCADE;"
        )

Here is the driver code that should turncate the tables with jdbc that is inside @AfterEach like so:

        dataSource.connection.use { connection -> {
                for (statement in tablesTobeCleared) {
                    val prepareStatement = connection.prepareStatement(statement)
                    prepareStatement.execute()
                    prepareStatement.close()
                    connection.commit()
                }
            }
        }

I get the same error, as mentioned above duplicate key when running tests.

PS: I have tried with this works


    @Autowired
    lateinit var jdbcTemplate: JdbcTemplate

    JdbcTestUtils.deleteFromTables(jdbcTemplate, "table1","table2");

But I want to remove table with TRUNCATE because it is more efficient and faster according to postgres docs here.

There is also cases where there is org.springframework.dao.DataIntegrityViolationException: so I need to use CASCADE as well. Is there a way to do this gracefully?

0 Answers
Related