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: |

‘Ban’ on Telegram 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. During a meeting with the president of the Supreme Electoral Court (TSE) on June 6, Telegram's Vice President Ilya Perekopsky announced the initiatives. According to the executive, Brazil is the first country in the world where Telegram is introducing the features, which could be expanded to other countries facing threats to democracy through the dissemination of false content. When choosing the right name for your Telegram channel, use the language of your target audience. The name must sum up the essence of your channel in 1-3 words. If you’re planning to expand your Telegram audience, it makes sense to incorporate keywords into your name. There have been several contributions to the group with members posting voice notes of screaming, yelling, groaning, and wailing in different rhythms and pitches. Calling out the “degenerate” community or the crypto obsessives that engage in high-risk trading, Co-founder of NFT renting protocol Rentable World emiliano.eth shared this group on his Twitter. He wrote: “hey degen, are you stressed? Just let it out all out. Voice only tg channel for screaming”.
from us


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