0Pricing
Spring Boot 4 Microservices & REST APIs · Урок

Реальные зависимости с Testcontainers

Тестируйте приложение с реальными базами данных в контейнерах

«Реальные зависимости с Testcontainers» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Microservices & REST APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Why Testcontainers

Testcontainers runs real services — PostgreSQL, Redis, Kafka — inside Docker containers during tests.

You test against the real database, not an in-memory substitute, catching dialect and behavior differences.

Adding the Dependency

Add the Testcontainers JUnit and database modules to your build.

// build.gradle
testImplementation "org.testcontainers:junit-jupiter"
testImplementation "org.testcontainers:postgresql"

The @Testcontainers Annotation

@Testcontainers on the test class activates container lifecycle management.

@Testcontainers
@SpringBootTest
class UserRepositoryIT {
    // containers declared here
}

Declaring a PostgreSQLContainer

A static @Container field defines the database image to start.

@Container
static PostgreSQLContainer<?> postgres =
    new PostgreSQLContainer<>("postgres:16")
        .withDatabaseName("testdb")
        .withUsername("test")
        .withPassword("test");

Wiring the Datasource

Use @DynamicPropertySource to inject the container's generated JDBC URL into Spring.

@DynamicPropertySource
static void props(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url",
        postgres::getJdbcUrl);
    registry.add("spring.datasource.username",
        postgres::getUsername);
    registry.add("spring.datasource.password",
        postgres::getPassword);
}

A Full Repository Test

Now repository tests run against real PostgreSQL.

@Test
void savesAndReads() {
    User saved = repository.save(new User("Alice"));
    assertThat(repository.findById(saved.getId()))
        .isPresent();
}

Static vs Instance Containers

A static container starts once for all tests in the class (faster). A non-static container restarts for each test (more isolation).

Other Container Types

Testcontainers has modules for many services.

@Container
static GenericContainer<?> redis =
    new GenericContainer<>("redis:7")
        .withExposedPorts(6379);

Reusing Containers

Enable container reuse to speed up local runs across test executions.

@Container
static PostgreSQLContainer<?> postgres =
    new PostgreSQLContainer<>("postgres:16")
        .withReuse(true);

Spring Boot Service Connections

Spring Boot 3.1+ can auto-configure the datasource from a container with @ServiceConnection, removing the need for @DynamicPropertySource.

@Container
@ServiceConnection
static PostgreSQLContainer<?> postgres =
    new PostgreSQLContainer<>("postgres:16");

Docker Requirement

Testcontainers needs a running Docker engine on the machine or CI agent. Without Docker the tests fail to start containers.

Quick Check

Test your understanding of Testcontainers.

Recap

You learned to test against real dependencies:

  • @Testcontainers + @Container start Docker services
  • PostgreSQLContainer for a real database
  • @DynamicPropertySource or @ServiceConnection wires the datasource
  • Requires a running Docker engine

Часто задаваемые вопросы

Урок «Реальные зависимости с Testcontainers» бесплатный?

Да — полный текст урока «Реальные зависимости с Testcontainers» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.

Чему я научусь в уроке «Реальные зависимости с Testcontainers»?

Тестируйте приложение с реальными базами данных в контейнерах Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?

Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Реальные зависимости с Testcontainers»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?

Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Модульное тестирование с JUnit и Mockito
  2. Тестирование веб-слоя с MockMvc
  3. Интеграционное тестирование с @SpringBootTest
  4. Реальные зависимости с Testcontainers
← Назад к Spring Boot 4 Microservices & REST APIs