spring-boot-2-template
45 строк · 1.7 Кб
1package by.andd3dfx.templateapp;
2
3import org.springframework.context.ApplicationContextInitializer;
4import org.springframework.context.ConfigurableApplicationContext;
5import org.springframework.core.env.ConfigurableEnvironment;
6import org.springframework.core.env.MapPropertySource;
7import org.testcontainers.containers.PostgreSQLContainer;
8import org.testcontainers.lifecycle.Startables;
9
10import java.util.Map;
11import java.util.stream.Stream;
12
13/**
14* According to https://reflectoring.io/spring-boot-flyway-testcontainers/
15*/
16public class IntegrationTestInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
17
18private static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine");
19
20@Override
21public void initialize(ConfigurableApplicationContext applicationContext) {
22startContainers();
23ConfigurableEnvironment environment = applicationContext.getEnvironment();
24
25MapPropertySource propertySource = new MapPropertySource(
26"test-containers", (Map) createConnectionConfiguration()
27);
28environment.getPropertySources().addFirst(propertySource);
29}
30
31private static void startContainers() {
32Startables.deepStart(Stream.of(postgres)).join();
33// we can add further containers
34// here like rabbitmq or other databases
35}
36
37private static Map<String, String> createConnectionConfiguration() {
38return Map.of(
39"DB_URL", postgres.getJdbcUrl(),
40"DB_USERNAME", postgres.getUsername(),
41"DB_PASSWORD", postgres.getPassword(),
42"DRIVER_CLASS_NAME", postgres.getDriverClassName()
43);
44}
45}
46