JAVAPROGLIB Telegram 6960
🎯 Интеграционные тесты с Testcontainers

Пошаговая настройка тестов на Spring Boot 3 с Testcontainers + PostgreSQL: быстро, изолированно, воспроизводимо.

1️⃣ Зависимости (Maven/Gradle)

— Maven (pom.xml):
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>1.20.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


— Gradle (Kotlin DSL):
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
testImplementation("org.flywaydb:flyway-core")
testImplementation("org.postgresql:postgresql")
testImplementation(platform("org.testcontainers:testcontainers-bom:1.20.3"))
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:postgresql")
}


2️⃣ Включаем Testcontainers

C Spring Boot 3.1 контейнер можно подключить одной аннотацией без ручного прописывания spring.datasource.*.
@Testcontainers
@ExtendWith(SpringExtension.class)
@SpringBootTest
class PostgresIT {

@Container
@ServiceConnection // Spring сам подставит URL/логин/пароль в DataSource
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("app")
.withUsername("app")
.withPassword("secret");

@Test
void contextLoads() {
// проверяем, что контекст и datasource поднялись на контейнере
}
}


3️⃣ Миграции для тестов (Flyway)

Положите миграции в src/test/resources/db/migration (отдельно от продовых — удобно для фикстур):
src/
└─ test/
└─ resources/
└─ db/
└─ migration/
├─ V1__init.sql
└─ V2__seed.sql


4️⃣ Ускоряем прогоны

▪️ Reusable containers (кэшируемый демон): добавьте в ~/.testcontainers.properties
testcontainers.reuse.enable=true

и .withReuse(true) для контейнера в тесте.

▪️ Singleton-паттерн контейнера: вынесите контейнер в общий абстрактный класс теста, чтобы один контейнер работал на все тесты.

5️⃣ Полезные трюки и подводные камни

— Если на MacOS/Colima, проверьте доступность Docker API (docker info) перед тестами.
— Для детерминизма фиксируйте теги образов (например, postgres:16-alpine), не latest.
— Логи контейнеров доступны: postgres.followOutput(...) — удобно для диагностики нестабильных тестов.
— Если нужен R2DBC: поднимайте Postgres как выше, а в application-test.yml указывайте r2dbc URL; @ServiceConnection корректно сконфигурирует оба коннектора, если они в classpath.
— Тяжёлые фикстуры → создавайте через SQL-маски (V*_seed.sql) или @Sql прямо в тестах — не смешивайте тестовые данные с продовыми миграциями.

🐸 Библиотека джависта

#Enterprise
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥8👍42



tgoop.com/javaproglib/6960
Create:
Last Update:

🎯 Интеграционные тесты с Testcontainers

Пошаговая настройка тестов на Spring Boot 3 с Testcontainers + PostgreSQL: быстро, изолированно, воспроизводимо.

1️⃣ Зависимости (Maven/Gradle)

— Maven (pom.xml):

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers-bom</artifactId>
<version>1.20.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>postgresql</artifactId>
<scope>test</scope>
</dependency>
</dependencies>


— Gradle (Kotlin DSL):
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
testImplementation("org.flywaydb:flyway-core")
testImplementation("org.postgresql:postgresql")
testImplementation(platform("org.testcontainers:testcontainers-bom:1.20.3"))
testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:postgresql")
}


2️⃣ Включаем Testcontainers

C Spring Boot 3.1 контейнер можно подключить одной аннотацией без ручного прописывания spring.datasource.*.
@Testcontainers
@ExtendWith(SpringExtension.class)
@SpringBootTest
class PostgresIT {

@Container
@ServiceConnection // Spring сам подставит URL/логин/пароль в DataSource
static PostgreSQLContainer<?> postgres =
new PostgreSQLContainer<>("postgres:16-alpine")
.withDatabaseName("app")
.withUsername("app")
.withPassword("secret");

@Test
void contextLoads() {
// проверяем, что контекст и datasource поднялись на контейнере
}
}


3️⃣ Миграции для тестов (Flyway)

Положите миграции в src/test/resources/db/migration (отдельно от продовых — удобно для фикстур):
src/
└─ test/
└─ resources/
└─ db/
└─ migration/
├─ V1__init.sql
└─ V2__seed.sql


4️⃣ Ускоряем прогоны

▪️ Reusable containers (кэшируемый демон): добавьте в ~/.testcontainers.properties
testcontainers.reuse.enable=true

и .withReuse(true) для контейнера в тесте.

▪️ Singleton-паттерн контейнера: вынесите контейнер в общий абстрактный класс теста, чтобы один контейнер работал на все тесты.

5️⃣ Полезные трюки и подводные камни

— Если на MacOS/Colima, проверьте доступность Docker API (docker info) перед тестами.
— Для детерминизма фиксируйте теги образов (например, postgres:16-alpine), не latest.
— Логи контейнеров доступны: postgres.followOutput(...) — удобно для диагностики нестабильных тестов.
— Если нужен R2DBC: поднимайте Postgres как выше, а в application-test.yml указывайте r2dbc URL; @ServiceConnection корректно сконфигурирует оба коннектора, если они в classpath.
— Тяжёлые фикстуры → создавайте через SQL-маски (V*_seed.sql) или @Sql прямо в тестах — не смешивайте тестовые данные с продовыми миграциями.

🐸 Библиотека джависта

#Enterprise

BY Библиотека джависта | Java, Spring, Maven, Hibernate




Share with your friend now:
tgoop.com/javaproglib/6960

View MORE
Open in Telegram


Telegram News

Date: |

Ng, who had pleaded not guilty to all charges, had been detained for more than 20 months. His channel was said to have contained around 120 messages and photos that incited others to vandalise pro-government shops and commit criminal damage targeting police stations. Click “Save” ; 5Telegram Channel avatar size/dimensions Invite up to 200 users from your contacts to join your channel Telegram Android app: Open the chats list, click the menu icon and select “New Channel.”
from us


Telegram Библиотека джависта | Java, Spring, Maven, Hibernate
FROM American