Dynamically add property sources to SpringBootTest

Tags: , , ,

Similar to Springboot unit test set @Configuration Properties dynamically but the context is different.

In my case I have a TestContainer running a custom MySQL database that is prepopulated with a lot of data (not using the SQL batch loading approach because the data is an anonymized copy of production and doing it through SQLs makes the boot up time of the container 20 minutes vs 2 minutes).

So far my test looks like this

    classes = {
public class ITFakeDB {
    public static final GenericContainer DB = new GenericContainer("devdb")
    private DataSource dataSource;

    private Users users;

    public void testDatabaseIsUp() {
        assertTrue(DB.getMappedPort(3306) != 0);

    public void testUser() {
        Optional<User> user = users.findByLoginName("mimi");

What I want to do is somehow set the spring.datasource.url (or in my case datasources.schema1.url because I did the routing datasource) to the one used by DB


You can manually override the property from within your Spring-boot test by using ContextConfiguration and ApplicationContextInitializer.

Override the property – define a static inner class:

  static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
      String url = "jdbc:mysql://" + DB.getContainerIpAddress() + ":" + DB.getMappedPort(3306) + "/my_db";

          .of("datasources.schema1.url=" + url)

Note: I have assumed that the url is derived from the ip address, port and db name. You may change that part as needed but the core idea remains.

ApplicationContextInitializer can be used for programmatically initializing a Spring context before context refresh. Now, wire up the context initializer class by annotating at test class level with ContextConfiguration:

@ContextConfiguration(initializers = Initializer.class)




Source: stackoverflow