> 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/43.-testing/43.3-testing-spring-boot-applications.md).

# 43.3 测试Spring Boot应用

Spring Boot应用只是一个Spring `ApplicationContext`，所以在测试时对它只需要像处理普通Spring context那样即可。

**注** 只有使用`SpringApplication`创建上下文时，外部配置、日志和Spring Boot的其他特性才会默认安装在上下文里。

Spring Boot提供一个`@SpringBootTest`注解。当你需要Spring Boot特性时，它可以作为标准的`spring-test``@ContextConfiguration`注解的另一种选择。该组件通过`SpringApplication`创建用于测试的`ApplicationContext`。

你可以使用`@SpringBootTest`的`webEnvironment`属性定义怎么运行测试：

* `MOCK`：加载`WebApplicationContext`，并提供一个mock servlet环境，使用该注解时内嵌servlet容器将不会启动。如果classpath下不存在servlet APIs，该模式将创建一个常规的non-web `ApplicationContext`。Can be used in conjunction with @AutoConfigureMockMvc for MockMvc -based testing of your application.
* `RANDOM_PORT`：加载`ServletWebServerApplicationContext`，并提供一个真实的servlet环境。使用该模式内嵌容器将启动，并监听在一个随机端口。
* `DEFINED_PORT`：加载`ServletWebServerApplicationContext`，并提供一个真实的servlet环境。使用该模式内嵌容器将启动，并监听一个定义好的端口（比如`application.properties`中定义的或默认的`8080`端口）。
* `NONE`：使用`SpringApplication`加载一个`ApplicationContext`，但不提供任何servlet环境（不管是mock还是其他）。

**注** 如果你的测试标注了`@Transactional`,默认的，在每一个测试方法结束时，它将会回滚事务。如果你正是此种情况，而且用了`RANDOM_PORT`或是`DEFINED_PORT`，隐式提供了一个真实的servlet环境。那么，HTTP客户端和服务端跑在不同的线程上，因此在不同的事务里。在这种情况下，任何在服务端初始化的事务不会回滚。

**注** 除了`@SpringBootTest`，还有许多另外的注解被提供，用来测试应用的更多特定的部分。你可以在这一章里找到更多细节。

**注** 不要忘记在测试用例上添加`@RunWith(SpringRunner.class)`，否则该注解将被忽略。
