> For the complete documentation index, see [llms.txt](https://jack80342.gitbook.io/spring-boot/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/46.-creating-your-own-auto-configuration/46.4-testing-your-auto-configuration.md).

# 46.4 测试你的自动配置

自动配置会受很多因素影响：用户配置（`@Bean`定义与`Environment`自定义）、状况评估（存在特定库）等。具体地，每个测试应当创建一个定义良好的`ApplicationContext`。它代表了那些自定义的结合。`ApplicationContextRunner`提供了达成这种目标的好办法。

`ApplicationContextRunner`经常会定义成测试类的实例变量，用来收集基础的、普遍的配置。下面的例子确保了`UserServiceAutoConfiguration`总是会被调用：

```java
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
        .withConfiguration(AutoConfigurations.of(UserServiceAutoConfiguration.class));
```

**注** 如果不得不定义多个自动配置，不需要对它们的声明排序，因为会和应用运行时完全相同的顺序调用它们。

每个测试可以使用runner代表一个特殊的使用案例。例如，下面的样本调用了一个用户配置（`UserConfiguration`），并且检查自动配置是否没有采用。调用`run`方法提供了一个回调上下文。它可以与`Assert4J`一起使用。

```java
@Test
public void defaultServiceBacksOff() {
    this.contextRunner.withUserConfiguration(UserConfiguration.class)
            .run((context) -> {
                assertThat(context).hasSingleBean(UserService.class);
                assertThat(context.getBean(UserService.class)).isSameAs(
                        context.getBean(UserConfiguration.class).myUserService());
            });
}

@Configuration
static class UserConfiguration {

    @Bean
    public UserService myUserService() {
        return new UserService("mine");
    }

}
```

也可以很容易地自定义`Environment`。如下所示：

```java
@Test
public void serviceNameCanBeConfigured() {
    this.contextRunner.withPropertyValues("user.name=test123").run((context) -> {
        assertThat(context).hasSingleBean(UserService.class);
        assertThat(context.getBean(UserService.class).getName()).isEqualTo("test123");
    });
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/46.-creating-your-own-auto-configuration/46.4-testing-your-auto-configuration.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
