Search code examples
javadatabasespring-bootkeycloaktestcontainers

Cleaning up the database between tests in Keycloak test container


I have a Spring Boot application where I use test containers for testing.

I want to clean up my database between tests. I create a user in the Keycloak test container to use its ID for my further tests, but this user is changing in almost every test and I want to delete that user and clean up the Keycloak's database after every test.

I created the Keycloak test container in this way:

@Container
static KeycloakContainer keycloakContainer = new KeycloakContainer()
            .withRealmImportFile("test-realm-export.json")
            .withAdminUsername("admin1")
            .withAdminPassword("admin1");

I can clean my MariaDB test container in the @AfterEach section using the following configuration.

@AfterEach
public void cleanUpEach() throws Exception {
   try (Connection connection = dataSource.getConnection()) {
     Resource resource = new ClassPathResource("/clean_up.sql");
     ScriptUtils.executeSqlScript(connection, resource);
   }
}

The clean_up.sql contains the following lines:

TRUNCATE TABLE table1;
TRUNCATE TABLE table2;

But the problem is that I don't know how to clean up the Keycloak's database too.


Solution

  • In the meantime I found a solution. I don't know if it is a workaround, but I want to share with you.

    Using a keycloak instance, I can delete the user I modify in every test.

        private Keycloak getKeycloakInstance() {
            return KeycloakBuilder.builder()
                    .serverUrl(keycloakContainer.getAuthServerUrl())
                    .realm("master")
                    .clientId("admin-cli")
                    .username(keycloakContainer.getAdminUsername())
                    .password(keycloakContainer.getAdminPassword())
                    .build();
        }
    

    And I put in the @AfterEach the following code:

    getKeycloakInstance().realm("test-realm").users().get(USER_ID).remove();
    

    Hope this helps!