# 7.11. 测试容器支持

除了[使用测试容器进行集成测试](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers)之外，还可以在开发时使用它们。下一节将提供更多相关细节。

**7.11.1. 在开发时使用测试容器**

这种方法允许开发人员快速启动应用程序所依赖的服务的容器，从而无需手动配置数据库服务器等内容。以这种方式使用 Testcontainers 提供与 Docker Compose 类似的功能，只不过您的容器配置采用 Java 而不是 YAML。

要在开发时使用测试容器，您需要使用“测试”类路径而不是“主”来启动应用程序。这将允许您访问所有声明的测试依赖项，并为您提供一个自然的位置来编写测试配置。

要创建应用程序的测试可启动版本，您应该在`src/test`目录中创建一个“Application”类。例如，如果您的主应用程序位于`src/main/java/com/example/MyApplication.java`，您应该创建`src/test/java/com/example/TestMyApplication.java`

`TestMyApplication`类可以使用`SpringApplication.from(…)`方法来启动真正的应用程序：

```
public class TestMyApplication {
​
    public static void main(String[] args) {
        SpringApplication.from(MyApplication::main).run(args);
    }
​
}
```

您还需要定义`Container`要与应用程序一起启动的实例。为此，您需要确保`spring-boot-testcontainers`模块已作为`test`依赖项添加。完成后，您可以创建一个`@TestConfiguration`类来声明要启动的容器的`@Bean`方法。

您还可以使用 `@ServiceConnection`注解您的`@Bean`方法来创建`ConnectionDetails`bean。有关支持的技术的详细信息，请参阅[服务连接部分。](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers.service-connections)

典型的测试容器配置如下所示：

```
@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {
​
    @Bean
    @ServiceConnection
    public Neo4jContainer<?> neo4jContainer() {
        return new Neo4jContainer<>("neo4j:5");
    }
​
}
```

> bean的生命周期`Container`由 Spring Boot 自动管理。容器将自动启动和停止。
>
> 您可以使用该`spring.testcontainers.beans.startup`属性来更改容器的启动方式。默认情况下使用`sequential`启动，但您也可以选择`parallel`如果您希望并行启动多个容器。

定义测试配置后，您可以使用`with(…)`方法将其附加到测试启动器：

```
public class TestMyApplication {
​
    public static void main(String[] args) {
        SpringApplication.from(MyApplication::main).with(MyContainersConfiguration.class).run(args);
    }
​
}
```

现在，您可以启动`TestMyApplication`像启动任何常规 Java`main`方法应用程序一样启动您的应用程序及其需要运行的容器。

> 您可以使用 Maven 目标`spring-boot:test-run`或 Gradle 任务`bootTestRun`从命令行执行此操作。

**在开发时贡献动态属性**

如果您想在开发时从您的`Container` `@Bean`方法贡献动态属性，您可以通过注入`DynamicPropertyRegistry`. 这与您可以在测试中使用的[`@DynamicPropertySource`注释](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers.dynamic-properties)的工作方式类似。它允许您添加容器启动后可用的属性。

典型的配置如下所示：

```
@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {
​
    @Bean
    public MongoDBContainer mongoDbContainer(DynamicPropertyRegistry properties) {
        MongoDBContainer container = new MongoDBContainer("mongo:5.0");
        properties.add("spring.data.mongodb.host", container::getHost);
        properties.add("spring.data.mongodb.port", container::getFirstMappedPort);
        return container;
    }
​
}
```

> 建议尽可能使用 `@ServiceConnection`，但是，对于尚不支持`@ServiceConnection`的技术，动态属性可能是一个有用的后备方案。

**导入测试容器声明类**

使用测试容器时的常见模式是将`Container`实例声明为静态字段。通常这些字段直接在测试类上定义。它们也可以在父类或测试实现的接口上声明。

例如，以下`MyContainers`接口声明`mongo`和`neo4j`容器：

```
public interface MyContainers {
​
    @Container
    @ServiceConnection
    MongoDBContainer mongoContainer = new MongoDBContainer("mongo:5.0");
​
    @Container
    @ServiceConnection
    Neo4jContainer<?> neo4jContainer = new Neo4jContainer<>("neo4j:5");
​
}
```

如果您已经以这种方式定义了容器，或者您只是喜欢这种样式，则可以导入这些声明类，而不是将容器定义为`@Bean`方法。为此，请将`@ImportTestcontainers`注释添加到您的测试配置类中：

```
@TestConfiguration(proxyBeanMethods = false)
@ImportTestcontainers(MyContainers.class)
public class MyContainersConfiguration {
​
}
```

> 如果您不打算使用[服务连接功能](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers.service-connections)但想使用[`@DynamicPropertySource`](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.testing.testcontainers.dynamic-properties)，请从`Container`字段中删除`@ServiceConnection`注释。您还可以将带`@DynamicPropertySource`注释的方法添加到声明类中。

**在开发时将 DevTools 与测试容器结合使用**

使用 devtools 时，您可以使用`@RestartScope` 来注释 bean 和 bean 方法。当开发工具重新启动应用程序时，不会重新创建此类 bean。这对于 Testcontainer `Container`bean 特别有用，因为尽管应用程序重新启动，它们仍保持其状态。

```
@TestConfiguration(proxyBeanMethods = false)
public class MyContainersConfiguration {
​
    @Bean
    @RestartScope
    @ServiceConnection
    public MongoDBContainer mongoDbContainer() {
        return new MongoDBContainer("mongo:5.0");
    }
​
}
```

> 如果您正在使用 Gradle 并希望使用此功能，则需要将`spring-boot-devtools`依赖项的配置从更改`developmentOnly`为`testImplementation`。使用默认范围`developmentOnly`，`bootTestRun`任务将不会获取代码中的更改，因为开发工具未处于活动状态。

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-boot-can-kao-wen-dang/7.-he-xin-te-xing/7.11.-ce-shi-rong-qi-zhi-chi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
