单元测试:基于Groovy的Spock框架

1.简介

Spock 框架是一个基于groovy语法的测试框架,由于使用groovy,所以使用起来比 junit 更加灵活,测试用例的写法更加简单易懂,一目了然。

如果使用过junit,spock的则很容易上手,可以类比来学习。

官网:http://spockframework.org
必读书籍:《Java Testing with Spock》
如要速成只需要阅读以下两篇文章:
5分钟入门Groovy:https://learnxinyminutes.com/docs/groovy/
一篇非常详尽的介绍Spock的英文教程:https://semaphoreci.com/community/tutorials/stubbing-and-mocking-in-java-with-the-spock-testing-framework

1. 测试方法的生命周期

在junit使用时,主要用以下注解来标记测试类的方法:

@Test :标记需要运行的测试方法,一个测试类中可以有多个@Test方法;
@Before/@After :标记的方法,会在每个测试方法运行之前/之后运行一次;
@BeforeClass/@AfterClass :标记的方法会在测试类初始化时/销毁时运行;

spock 没有使用以上的注解形式,而是测试类需要继承 Specification 父类,重写父类中的以下方法,就可以自定义测试方法的生命周期:

def setup() {}         // run before every feature method
def cleanup() {}       // run after every feature method
def setupSpec() {}     // run before the first feature method
def cleanupSpec() {}   // run after the last feature method

2. 测试方法的格式

(1)given … expect … 格式:

given语句块为条件,expect为测试期望得到的结果,结果为true则通过测试。上面的示例就是这种格式的。

2)given … when … then …

class CalculateSpec extends Specification {
@Shared
CalculateService calculateService
// 初始化
def setupSpec() {
calculateService = new CalculateService()
}
// 测试方法
def “test plus 1”() {
given: “准备数据”
def a = 1
def b = 2
when: “测试方法”
def c = calculateService.plus(a, b)
then: “校验结果”
c == 4 - 1
}

其中,@Share注解表示的是各个测试方法共享的一个实例。setupSpec() 方法中初始化了这个实例。

(3)when … then …

语义同上。

(4)given … expect … where …

def “test1”() {
given: “准备数据”
expect: “测试方法”
z == calculateService.plus(x, y)
where: “校验结果”
x | y || z
1 | 0 || 1
2 | 1 || 3
}

expect 为核心的测试校验语句块。where 为多个测试用例的列举,很直观的写法。

以上测试方法的语义为:z是由x和y经过方法plus()运算后得到的结果,现在分别列出了两组x,y,z的值,来测试这个关系是否满足。

由于有两个测试用例,所以plus()方法会在这里运行两次。

(5)expect … where …

同上。

(6)expect …

同上。测试单个语句是否成立。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值