单元测试spock框架基础

spock基础

1:fields 字段(属性)


2:fixture methods 骨架方法
def setup(){} 每个功能(测试)方法之前执行的方法
def cleanup(){} 每个功能(测试)方法之后执行的方法
def setupSpec(){} 第一个功能(测试)方法之前执行的方法
def cleanupSpec(){} 最后一个功能(测试)方法之后执行的方法


3:feature methods 功能(测试)方法
def "sum should return param1+param2"(){
expect:
sum.sum(1,2) == 3
}

4:blocks 每个feature method又被划分为不同的block,不同的block处于测试执行的不同阶段,在测试运行时,各个block按照不顺序和规则被执行
4.1 setup/given block 在这个block中会放置与这个测试函数相关的初始化程序 *** 放在功能(测试)方法最前面 ***
4.2 when: then: block when和then是搭配使用,在when执行待测试的函数,在when中判断是否符合预期
4.3 assert 断言
在expect: then:会默认assert所有返回值是boolean型的顶级语句
异常断言 thrown(Exception)
没有抛出异常 notThrown(Exception)

5:where blocks
传统的测试边界、测试异常分支,依赖反复调用:
Math.max(1,3) == 3 Math.max(7,3) == 7 Math.max(0,0) == 0 //这里调用了三次
spock框架,提供了优雅:
expect:
Math(a,b) == c
where:
a | b | || c
1 | 3 | || 3
7 | 3 | || 7
0 | 0 | || 0

6:交互测试(模块与模块之间) 类S,依赖类D提供的m方法
class S{
private D d;

public S(D d){
this.d = d;
}
public void t(){
boolean sData = d.m(String str);
return b ? "ok" : "fail";
}
}
class D{
public boolean m() {
return false;
}
}
测MOCK可以分为以下几个步骤:
1) 通过Mock(D)来得到一个类D的实例; d = Mock(D)
2) 在setup()方法中将d设置为类S的使用实例; S s = new S(d)
3) 在given block中,给出m方法的模拟返回数据; sData = true
4) 在when block中,调用D的方法,使用 >> 将输出指向 sData; d.m(_ as String) >> sData
5) 在then方法中,给出判定表达式,其中判定表达式可以引用where子句的变量; s.t() == "ok"

class STest extends Specification {
D d = Mock(D) //step 1
S s

def setup() {
s = new S(d) //step 2
}

def "T"() {
given:
def sData = true //step 3
when:
d.m() >> sData //step 4
then:
s.t() == "ok" //step 5
}
}


参考文档:
http://blog.2baxb.me/archives/1398
http://www.mamicode.com/info-detail-2233681.html (mock)

posted @ 2019-04-25 20:54  amu2018  阅读(678)  评论(0编辑  收藏  举报