TestContainer SpringBoot tests

Arpitsharma
1 min readJul 17, 2021

TestContainers provides easiest way to run truly independent integration tests. One of the most challenging way to use Postgres Database Test Containers and integrate it in to the test. Please see below some of the steps to include container and pass the dynamic connection details to the Repositories.

  1. Create the container using GenericContainer or any specific, please see below the code to create container. Using Postgres test container implementation as below:
testImplementation "org.testcontainers:postgresql:1.15.3"

2. Create the container instance, and add the sql path, it creates the instance and executes the queries and makes DB ready to be used

PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(POSTGRES_TEST_IMAGE).withInitScript("somepath/init_postgresql.sql")

3. Override Datasource Bean — the most important Step. This overrides any other data-source initialized in SpringBoot. You can add these bean to a TestConfigration class which can be imported into the SpringBootTest.

@Configuration
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Testcontainers
public class TestConfiguration{

PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>(POSTGRES_TEST_IMAGE)
.withInitScript("somepath/init_postgresql.sql")


@Primary
@Bean
public DataSource dataSource(){
HikariConfig hikariConfig=new HikariConfig();
hikariConfig.setJdbcUrl(postgres.getUrl());
hikariConfig.setUsername(postgres.getUsername());
hikariConfig.setPassword(postgres.getPassword());
hikariConfig.setDriverClassName(postgres.getDriverClassName());
HikariDataSource hikariDataSource=new HikariDataSource(hikariConfig);
return hikariDataSource;
}
}

4. Create SpringBoot Test for DataSource class: Inorder to test Datasoruce configurations or Repositories just write SpringBoot test for the datasoruce class and import above specified datasource in it. This overrides the datasource in the repositories with posgtressContaier’s datasoruce and your repository can query on the test data.

@ExtendWith({SpringExtension.clas})
@SpringBootTest(classes = {DataSourceConfiguration.class, TestConfigration.class})
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@Testcontainers
public class RdSRepoTest {

@Autowired
TestRepository testRepository;

@Test
public void testRepo() {
System.out.println("*****************" + testRepository.existsById(1L));
}

}

This enables you to run your application or test your repositories without overriding your datasource properties statically with @DynamicPropertySource

--

--