> 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");
    });
}
```
