Spring Boot Starter Test

2025 年 3 月 18 日 | 3 分钟阅读

spring-boot-starter-test 是测试的主要依赖项。它包含我们测试所需的大部分元素。

我们可以编写几种不同类型的测试来帮助测试和自动化应用程序的运行状况。在开始任何测试之前,我们需要集成测试框架。

使用 Spring Boot,我们需要将 starter 添加到我们的项目中,对于测试,我们只需要添加 spring-boot-starter-test 依赖项。

它会拉取与测试相关的所有依赖项。添加它之后,我们可以构建一个简单的单元测试。我们可以通过 IDE 创建 Spring Boot 项目,也可以使用 Spring Initializr 生成它。

注意:如果您手动添加测试依赖项,请将其添加到 pom.xml 文件的底部。

在上面的依赖项中,需要注意的是它包含测试范围 <scope>test</scope>。这意味着当应用程序被捆绑和打包以进行部署时,任何使用测试范围声明的依赖项都会被忽略。测试范围依赖项仅在开发和 Maven 测试模式下可用。

当我们创建一个简单的 Spring Boot 应用程序时,默认情况下,它在 pom.xml 文件中包含测试依赖项,并在 src/test/java 文件夹下包含 ApplicationNameTest.java 文件。

让我们创建一个简单的 maven 项目。

Spring Boot Starter Test 示例

步骤 1: 打开 Spring Initializr https://start.spring.io/。

步骤 2: 提供 Group 名称和 Artifact Id。我们提供了 Group 名称 com.javatpoint 和 Artifact spring-boot-test-example

步骤 3: 添加 Spring Web 依赖项。

Spring Boot Starter Test

步骤 4: 单击 Generate 按钮。 当我们单击 Generate 按钮时,它会包装与项目相关的所有规范,并将 Jar 文件下载到我们的本地系统。

步骤 5: 解压缩下载的 Jar 文件。

步骤 6: 将文件夹导入到 STS。 导入需要一些时间。

File -> Import -> Existing Maven Projects -> Browse -> 选择文件夹 spring-boot-test-example -> Finish

导入项目后,我们可以在 STS 的 Package Explorer 部分中看到以下项目目录。

Spring Boot Starter Test

我们可以在上面的目录中看到它包含一个名为 SpringBootTestExampleApplicationTest.java 的测试文件,该文件位于 src/test/java 文件夹中。

SpringBootTestExampleApplicationTest.java

上面的代码默认实现两个注解:@SpringBootTest@Test

  • @SpringBootTest:它应用于运行基于 Spring Boot 的测试的测试类。它在常规 Spring TestContext Framework 之上提供了以下功能
    • 如果未定义任何特定的 @ContextConfiguration(loader=...),它将使用 SpringBootContextLoader 作为默认的 ContextLoader。
    • 当不使用嵌套的 @Configuartion 并且未指定任何显式类时,它会自动搜索 @SpringBootConfiguration
    • 它为不同的 WebEnvironment 模式提供支持。
    • 它注册一个 TestRestTemplate 或 WebTestClient bean,以用于使用 Web 服务器的 Web 测试。
    • 它允许使用 args attribute 定义应用程序参数。

步骤 7: 打开 SpringBootTestExampleApplicationTest.java 文件并将其作为 Junit Test 运行。

Spring Boot Starter Test

当我们运行上面的代码时,它会显示以下内容

Spring Boot Starter Test
下一个主题Spring Boot DevTools