背景:
最近部门要求提升测试的覆盖率,并推荐使用了 spock 框架,本着提高自己的能力的想法,放弃了 spring-test ,Junit 的测试框架我使用了大佬推荐的 Spock 框架,结果发现只有我选择了这个推荐的框架,不得不说如果单纯是为了工作,spock 的学习成本还是挺高的,整个过程就是一步一个坑,既然选择了就不能放弃,所以写一份教程吧。(有简单模式的时候千万不要去挑战自己的能力)。
本教程参考的主要资料也是官方文档,spock 是基于 groovy 语言的,我在此之前没有使用过 groovy 语言,虽然有一定的学习成本但是收益还是很可观的。
教程使用的框架 SpringBoot+Maven
一、准备
1.1、maven 依赖
<dependency> <groupId>org.spockframework</groupId> <artifactId>spock-spring</artifactId> <version>1.3-groovy-2.4</version> <scope>test</scope> </dependency>
建议使用 1.2 版本以上,因为 1.2 以上的版本才支持将 mock 的对象注入到 springContext 中。
原文如下:
Spock 1.2 adds support for exporting mocks from a Specification into an ApplicationContext.This was inspired by Spring Boot’s `@MockBean` (realised via Mockito) but adapted to fit into Spock style. It does not require any Spring Boot dependencies, however it requires Spring Framework 4.3.5 or greater to work. Spock’s `@SpringBean` actually creates a proxy in the `ApplicationContext` which forwards everything to the current mock instance. The type of the proxy is determined by the type of the annotated field. The proxy attaches itself to the current mock in the setup phase, that is why the mock must be created when the field is initialized.
1.2、测试类的创建
测试样例:
class MathSpec extends Specification { def setup() { } def "maximum of two numbers"() { expect: // exercise math method for a few different inputs Math.max(1, 3) == 3 Math.max(7, 4) == 7 Math.max(0, 0) == 0 } }
简单的测试可以,后续继续介绍 spock 的简单的语法。
1.3、基本的构造块
Spock 提供了如下基本构造块:
- where: 以表格的形式提供测试数据集合
- when: 触发行为,比如调用指定方法或函数
- then: 做出断言表达式
- expect: 期望的行为,when-then 的精简版
- given: mock 单测中指定 mock 数据
- thrown: 如果在 when 方法中抛出了异常,则在这个子句中会捕获到异常并返回
- def setup() {} :每个测试运行前的启动方法
- def cleanup() {} : 每个测试运行后的清理方法
- def setupSpec() {} : 第一个测试运行前的启动方法
- def cleanupSpec() {} : 最后一个测试运行后的清理方法
使用这些基本构造块来编写单测。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于