这是我参与8月更文挑战的第15天,活动详情查看:8月更文挑战
上一篇文章简单介绍了一下spock的概念,这篇文章开始从实战角度一步步学习spock的应用。因为整个的测试代码都需要用groovy来写,如果有必要的话,可以简单学一些groovy这门语言。如果不想学,用官方给的demo也能完全覆盖基本的需要。
spock有一些重要的概念:
Specification
这是spock的基础类,里面含有大量比较重要的方法。每一个单测类都会继承这个类。
Fields
这里会定义很多字段,这属于setup阶段,把需要mock的spring bean或者mock之后的返回在这里定义。举个例子:
def studentDao = Mock(StudentDao)
def tester = new StudentService(studentDao: studentDao)
...
given: "设置请求参数"
def student1 = new StudentDTO(id: 1, name: "张三", province: "北京")
def student2 = new StudentDTO(id: 2, name: "李四", province: "上海")
复制代码
Fixture Methods
固定的方法。这里是Specification中预置的一些方法,有以下几种:
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
复制代码
可以理解为数据的预热,和执行完的清理。这在junit中也有类似的概念,作为单元测试必备的方法。
Feature Methods
这就是spock比较优秀的地方了。它规定了一些既定的测试步骤,甚至让非技术人员也能一眼看明白,并且书写也极为简单。分为以下几种:
动态方法名
在执行单测时,每push一个元素,都是按照下面的文字打印出来,尤其适合那些if/else的分支
def "pushing an element #element on the stack"() {
// blocks go here
}
复制代码
Given Blocks
顾名思义,这里是输入,可以带一些说明:
given: "setup new stack and input elemet"
def stack = new Stack()
def elem = "push me"
复制代码
given
是可选的,可以用setup()方法代替。
When and Then Blocks
也非常好理解,就是当某条件发生时,结果应当为什么。跟junit中的assert比较相似。举个例子:
when: "push stack"
stack.push(elem)
then: "check stack status"
!stack.empty
stack.size() == 1
stack.peek() == elem
复制代码
这里的操作非常的多,覆盖面也非常广,但基本上是boolean操作,也包含了exception的判断。后续可以慢慢说。
Expect Blocks
这个和when/then操作比较类似,更适合那种相对简单的判定,比如只是一行表达式的判定:
when:
def x = Math.max(1, 2)
then:
x == 2
复制代码
expect:
Math.max(1, 2) == 2
复制代码
节省代码,也更简洁明了。
Cleanup Blocks
清道夫的角色,需要释放一些资源,不然可能会其他的测试case产生影响。
given:
def file = new File("/some/path")
file.createNewFile()
// ...
cleanup:
file.delete()
复制代码
当然你可以选择使用cleanup()方法,但使用cleanup块更加灵活。
Where Blocks
Where永远是最后一个块,而且不能重复,这会在Data Driven Testing中有更大的用处,简单举个例子:
def "computing the maximum of two numbers"() {
expect:
Math.max(a, b) == c
where:
a << [5, 3]
b << [1, 9]
c << [5, 9]
}
复制代码
expect中声明了计算公式,where中可以针对这个公式做多种计算和预期。这里的含义是,当a=5,b=1则c=5;当a=3,b=9则c=9,这里按照求最大值的方法计算了最大值。