DEV Community

loading...

DB Testing with TestContainers

Dan
・1 min read

Testing, as we all know is a very important part of development, but it is not always easy to do!

Trying to find a way to test querying databases was very tough, at least I thought so anyway. From doing some research online there was one of two ways to test this;

  1. Use mocks
  2. Use an embedded db - including testcontainers in this

Personally I don't like mocks, so that was option 1 ruled out.

Using testcontainers in code was great and worked very well but I had a slight problem. For the life of me I could not get the database to reset between tests. If I were to run the tests individually, all would be good. But when I run a suite of tests at once they fail because the db isn't reset.

With a Quarkus setup I was able to find out that if you annotate the class with @TestTransaction, then after each test the db is rolled back.

@QuarkusTest
@TestTransaction
public class TestClass {

    @ClassRule
    private static PostgreSQLContainer dbContainer = new PostgreSQLContainer("postgres-image")
            .withDatabaseName("dbname")
            .withUsername("username")
            .withPassword("password");

    @Test
    public void myTest() {}


    @Test
    public void myTest_2() {}
Enter fullscreen mode Exit fullscreen mode

Now with the two tests, you can run them as a suite and the db will be reset after each test is finished.

Happy testing

Discussion (0)