0

I'm trying to use TestContainer for an integration test of a Spring Boot application.

The database of such application resides in a custom PostgreSQL Docker image.

In the integration test the ApplicationContext is started through MockMvc and the container is started with something like

public class ITMyServiceTest {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Rule
  public PostgreSQLContainer testPostgres = new PostgreSQLContainer("my-custom-database-image")
           .withDatabaseName("my_db")
           .withUsername("my_name")
           .withPassword("my_pwd");

  @Test
  public void shouldDoSomething() throws Exception {
    this.mockMvc.perform(get("/api/do/something")).andDo(print());
  }

What happens now is that the container is started, but the application context doesn't refer to it.

I can't use the JDBC URL scheme (like spring.datasource.url=jdbc:tc:postgresql://localhost/my_db) in a .properties file because:

  • if I specify postgresql as server it will start another server and the context will use it

  • if I specify the name of my container (or everything else) the test will rightly raise a java.lang.IllegalArgumentException because it is not a known database type.

How can I set the Spring' application context to refer to my container?

AleG
  • 108
  • 9

1 Answers1

0

You can probably have different application.properties like application-it.properties and there define integration test specific configuration properties as - @TestPropertySource(locations = {"classpath:application-it.properties" } or have different profile(s) active during integration tests , like -@ActiveProfiles(AppConstants.INTEGRATIONTEST)

So I guess you would like to set your application's database port to the randomly generated database port. If that's the case then can first expose the port :

public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("my-custom-database-image")
       .withDatabaseName("my_db")
       .withUsername("my_name")
       .withPassword("my_pwd")
       .withExposedPorts(5432);

Following that when you are setting the spring.datasource.url, you can set there the randomly generated port(which is mapped against the exposed port) from the postgresql container, how to set dynamic values inside application properties is shown in this blog post

kazi
  • 99
  • 5
  • The database container is generated with a random port, so I cannot put it in an `application.properties` – AleG Aug 30 '19 at 13:24