1. 简介
在本篇简短的教程中,我们将展示如何将 Spring Boot 的 测试框架 与 Spock 框架 的表现力结合起来,无论你是做单元测试还是 集成测试,都能获得事半功倍的效果。
2. 项目搭建
我们从一个简单的 Web 应用开始。它支持通过 REST 接口进行问候、修改问候语以及重置为默认问候语。除了主类外,我们使用一个简单的 @RestController
来提供这些功能:
@RestController
@RequestMapping("/hello")
public class WebController {
@GetMapping
public String salutation() {
return "Hello world!";
}
}
这个 Controller 会返回 “Hello world!”。@RestController
注解以及 快捷的映射注解 确保了 REST 接口的自动注册。
3. Maven 依赖配置:Spock 与 Spring Boot Test
我们首先添加 Maven 依赖项,如有必要还需配置 Maven 插件。
3.1. 添加 Spock 框架依赖(含 Spring 支持)
为了使用 Spock 框架本身 以及 对 Spring 的支持,我们需要添加如下两个依赖:
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>2.4-M4-groovy-4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>2.4-M4-groovy-4.0</version>
<scope>test</scope>
</dependency>
⚠️ 注意:版本号中包含了所依赖的 Groovy 版本。
3.2. 添加 Spring Boot Test 依赖
为了使用 Spring Boot Test 提供的测试工具,我们需要添加以下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>3.2.1</version>
<scope>test</scope>
</dependency>
3.3. 配置 Groovy 环境
由于 Spock 是基于 Groovy 的,**我们必须添加并配置 gmavenplus-plugin**,以便在测试中使用 Groovy 语言:
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>3.0.2</version>
<executions>
<execution>
<goals>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
</plugin>
⚠️ 注意:因为我们只在测试中使用 Groovy,所以插件的目标被限定为 compileTests
。
4. 在 Spock 测试中加载 ApplicationContext
一个简单的测试是 验证 Spring 应用上下文中所有 Bean 是否都已成功创建:
@SpringBootTest
class LoadContextTest extends Specification {
@Autowired (required = false)
private WebController webController
def "when context is loaded then all expected beans are created"() {
expect: "the WebController is created"
webController
}
}
在这个集成测试中,我们需要启动 Spring 的 ApplicationContext
,而 @SpringBootTest
注解正好帮我们做了这件事。Spock 使用 “when”、“then” 或 “expect” 等关键字来划分测试结构,非常清晰。
另外,我们可以利用 Groovy Truth 来判断对象是否为 null,比如最后一行的 webController
就是如此。
5. 在 Spock 测试中使用 WebMvcTest
同样地,我们也可以测试 WebController
的行为:
@AutoConfigureMockMvc
@WebMvcTest
class WebControllerTest extends Specification {
@Autowired
private MockMvc mvc
def "when get is performed then the response has status 200 and content is 'Hello world!'"() {
expect: "Status is 200 and the response is 'Hello world!'"
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andReturn()
.response
.contentAsString == "Hello world!"
}
}
✅ 重点提醒:在 Spock 的测试类(或称 Specification)中,我们可以使用所有熟悉的 Spring Boot 测试注解,和写 Java 测试时一模一样。
6. 总结
本文介绍了如何配置 Maven 项目,以便结合使用 Spock 和 Spring Boot 的测试框架。同时我们也看到了这两个框架是如何完美互补的。
如果你想要深入了解,可以查阅我们关于 Spring Boot 测试、Spock 框架 以及 Groovy 语言 的更多教程。
📌 最后,完整的源代码和更多示例可以在我们的 GitHub 仓库 中找到。