起因
刷题的时候,写完了代码,总是需要有单元测试验证自己的代码对不对。以前的我比较蠢,实在main方法里面测试我写的逻辑对不对的。这种写法,耗时不说,一个类里面只能有一个main方法,导致我写另外一题时,就把上一题的单元测试数据丢了,这样很不好。所以推荐下大家用spock做单元测试。
spock的pom文件导入
<!-- Spock依赖 -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.1-groovy-2.4</version>
<scope>test</scope>
</dependency>
<!-- Spock需要的groovy依赖 -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.15</version>
</dependency>
单元测试流程
在test目录下面,创建groovy文件,我创建了一个SolutionTest
此类需要继承spock的基类Specification,才能有后续的处理功能
全局创建要测试的对象,用def创建测试方法,在里面写测试逻辑即可
运行后会输出测试用例的运行结果
spock语法介绍
一个spock方法由四部分组成
- 变量字段:全局定义下测试方法里面需要频繁用到的对象,属性
- 测试模板方法:测试方法运行前和运行后执行的方法
def setupSpec() {} // runs once - before the first feature method
def setup() {} // runs before every feature method
def cleanup() {} // runs after every feature method
def cleanupSpec() {} // runs once - after the last feature method
- 测试方法:我们要测试的代码的主体
- 测试帮助方法:没怎么用过
测试方法书写
def "test count"() {
given: //前置参数
when: //执行需要测试的代码
then: //验证执行结果
where: //参数赋予不同值
}
测试方法主要有四部分组成,功能如备注所示
def "test count1"() {
given:
Solution solution = new Solution()
when: // 执行需要测试的代码
int a = solution.count1(n)
then: // 验证执行结果
a == b
where: //n和b的赋值
n | b
1 | 1
2 | 1
}
上面为举例模板,我在given里面定义我要测试的对象,在when里面,调用了对象里面的计算方法。then里面添加了判断语句,a是结果,b是我预期的结果,两个需要相等那方法的逻辑就没有问题。where里面我给n和b赋值,相当于提供了测试用例。
可以看到执行了两组测试,很是方便。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。