Testing
Spring Boot 提供了许多工具和注解,以帮助测试你的应用程序。
测试支持由两个通用模块提供:spring-boot-test 包含核心项,spring-boot-test-autoconfigure 支持测试的自动配置,以及多个专用的 -test 模块,用于为特定功能提供测试支持。
大多数开发者使用 spring-boot-starter-test starter,它会导入通用的 Spring Boot 测试模块,以及 JUnit Jupiter、AssertJ、Hamcrest 和许多其他有用的库,还会导入适用于其特定应用程序的专用 -test 模块。
如果你有使用 JUnit 4 编写的测试,可以使用 JUnit 6 的 vintage 引擎来运行它们。要使用 vintage 引擎,请添加对 junit-vintage-engine 的依赖,如下例所示:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
hamcrest-core 被排除,以使用作为 spring-boot-starter-test 一部分的 org.hamcrest:hamcrest。
章节总结
📄️ 测试模块
Spring Boot 提供了几个专注于特定功能的 -test 模块:
📄️ 测试范围依赖项
spring-boot-starter-test starter(在 test scope 中)包含以下提供的库:
📄️ 测试 Spring 应用程序
依赖注入的主要优势之一是它应该使你的代码更容易进行单元测试。你可以直接使用 new 操作符来实例化对象,而无需涉及 Spring。你也可以使用模拟对象(mock objects)来替代真实的依赖。
📄️ 测试 Spring Boot 应用程序
Spring Boot 应用程序就是一个 Spring ApplicationContext,因此除了对普通的 Spring 上下文通常所做的测试之外,不需要做任何特别的事情来测试它。
📄️ Testcontainers
Testcontainers 库提供了一种管理运行在 Docker 容器中的服务的方式。它与 JUnit 集成,允许你编写一个测试类,在任何测试运行之前启动一个容器。Testcontainers 在编写与真实后端服务(如 MySQL、MongoDB、Cassandra 等)交互的集成测试时特别有用。
📄️ 测试工具
一些在测试应用程序时通常很有用的测试工具类被打包在 spring-boot 中。