一、导入依赖

Spock是基于JUnit的单测框架,提供一些更好的语法,结合Groovy语言,可以写出更为简洁的单测。

<!-- groovy依赖 -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.0</version>
</dependency>
<!-- spock核心依赖 -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-core</artifactId>
<version>1.3-groovy-2.4</version>
<scope>test</scope>
</dependency>
<!-- spring spock依赖 -->
<dependency>
<groupId>org.spockframework</groupId>
<artifactId>spock-spring</artifactId>
<version>1.3-groovy-2.4</version>
<scope>test</scope>
</dependency>
<!-- 单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>

二、测试例子

继承Specification

package com.qiang.groovy.controller

import com.qiang.groovy.controller.ConfigInfoController
import spock.lang.Specification class ConfigInfoControllerGroovy extends Specification { }

固定方法

/**
* 在第一个测试方法开始前执行一遍
*/
def setupSpec() {
println "------------ setupSpec()方法 ------------"
} /**
* 每个测试方法开始前都会执行一遍
*/
def setup() {
println "------------ setup()方法 ------------"
} /**
* 每个测试方法后都会执行一遍
*/
def cleanup() {
println "------------ cleanup()方法 ------------"
} /**
* 最后一个测试方法后执行
*/
def cleanupSpec() {
println "------------ cleanupSpec()方法 ------------"
}

测试例子

def "测试a>b"() {
given:
def a = new Random().nextInt(10)
def b = 2
expect:
println a
a > b
}

点击运行

测试通过

测试不通过

三、基本构造

  • where: 以表格的形式提供测试数据集合
  • when: 触发行为,比如调用指定方法或函数
  • then: 做出断言表达式
  • expect: 期望的行为,when-then的精简版
  • given: mock单测中指定mock数据
  • thrown: 如果在when方法中抛出了异常,则在这个子句中会捕获到异常并返回
  • def setup() {} :每个测试运行前的启动方法
  • def cleanup() {} : 每个测试运行后的清理方法
  • def setupSpec() {} : 第一个测试运行前的启动方法
  • def cleanupSpec() {} : 最后一个测试运行后的清理方法

四、构造例子

4.1 expect-where

在where子句中以表格形式给出一系列输入输出的值,然后在expect中引用。

@Unroll
def "测试expect-where"() {
expect:
userInfoService.getById(id).getName() == name
where:
id | name
1 | "小强"
2 | "傻狗"
3 | "小猪"
}

4.2 given-when-then

当条件满足时,达到期望的结果。

@Unroll
@Transactional
def "测试given-when-then"() {
given:
// 数据准备
UserInfo userInfo = new UserInfo()
userInfo.setName("小强崽")
userInfo.setAsset(10000000.00)
when:
// 条件判断
boolean flag = userInfoService.save(userInfo)
then:
// 期望结果
flag
}

4.3 when-then-thrown

测试异常信息。

/**
* 模拟异常
*/
@Override
public void getExceptionMessage() {
throw new RuntimeException("模拟异常");
}

测试方法。

def "测试异常thrown"() {
when:
// 此方法会抛出RuntimeException
userInfoService.getExceptionMessage()
then:
// 接收异常
def ex = thrown(Exception)
ex.class.name == "java.lang.RuntimeException"
ex.getMessage() == "模拟异常"
}

五、远程挡板

远程调用第三方服务需要Mock挡板,避免受第三方服务的影响。

远程调用服务

package com.qiang.groovy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiang.common.response.ResponseResult;
import com.qiang.groovy.entity.UserInfo;
import com.qiang.groovy.feign.GiteeServiceFeign;
import com.qiang.groovy.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.io.Serializable;
import java.util.List; /**
* @author 小强崽
* @create: 2021-04-11 21:31:14
* @description: 控制层
*/
@RestController
@RequestMapping("/user/info")
public class UserInfoController {
/**
* 注入远程调用接口
*/
@Autowired
private GiteeServiceFeign giteeServiceFeign; /**
* 远程调用
*
* @param msg
* @return
*/
@GetMapping("/gitee/test/feign")
public ResponseResult<String> testFeign(@RequestParam("msg") String msg) {
return giteeServiceFeign.testFeign(msg);
}
}

远程调用做挡板后,自定义挡板返回的参数即可。

package com.qiang.groovy.controller

import com.qiang.common.response.ResponseResult
import com.qiang.common.util.SpringContextUtil
import com.qiang.groovy.feign.GiteeServiceFeign
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Specification @SpringBootTest
class UserInfoControllerGroovy extends Specification { @Autowired
private UserInfoController userInfoController @Autowired
private SpringContextUtil springContextUtil; /**
* 单元测试调用第三方服务时,需要做挡板
*/
def giteeServiceFeign = Mock(GiteeServiceFeign) def "测试远程调用"() {
given:
// 定义挡板返回的参数,(*_)为任意入参参数
giteeServiceFeign.testFeign(*_) >> ResponseResult.success()
expect:
userInfoController.testFeign(msg).code == result
where:
msg | result
"msg" | "200"
} /**
* 每个测试方法开始前都会执行一遍
*/
def setup() {
// 挡板赋值
userInfoController.giteeServiceFeign = giteeServiceFeign
} /**
* 每个测试方法后都会执行一遍
*/
def cleanup() {
// 还原挡板
userInfoController.giteeServiceFeign = springContextUtil.getBean(GiteeServiceFeign.class)
} }

六、常用注解

6.1 @Unroll

某个测试用例失败了,却难以查到是哪个失败了,这时候,可以使用@Unroll注解,该注解会将where子句的每个测试用例转化为一个 @Test 独立测试方法来执行,这样就很容易找到错误的用例。

@Unroll
def "测试getById()"() {
expect:
userInfoService.getById(id).getName() == name
where:
id | name
1 | "小强"
2 | "傻狗"
3 | "小猪"
}

没加@Unroll之前

加了@Unroll之后

6.2 @Transactional

插入数据时,加上该注解测试完成会回滚数据。

作者(Author):小强崽

来源(Source):https://www.wuduoqiang.com/archives/Groovy+Spock单元测试

协议(License):署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)

版权(Copyright):商业转载请联系作者获得授权,非商业转载请注明出处。 For commercial use, please contact the author for authorization. For non-commercial use, please indicate the source.

Groovy+Spock单元测试的更多相关文章

  1. 使用Groovy+Spock构建可配置的订单搜索接口测试用例集

    概述 测试是软件成功上线的安全网.基本的测试包含单元测试.接口测试.在 "使用Groovy+Spock轻松写出更简洁的单测" 一文中已经讨论了使用GroovySpock编写简洁的单 ...

  2. Groovy/Spock 测试导论

    Groovy/Spock 测试导论 原文 http://java.dzone.com/articles/intro-so-groovyspock-testing 翻译 hxfirefox 测试对于软件 ...

  3. 使用Groovy+Spock轻松写出更简洁的单测

    当无法避免做一件事时,那就让它变得更简单. 概述 单测是规范的软件开发流程中的必不可少的环节之一.再伟大的程序员也难以避免自己不犯错,不写出有BUG的程序.单测就是用来检测BUG的.Java阵营中,J ...

  4. Compile Groovy/Spock with GMavenPlus

    在之前的博文里曾使用GMaven插件编译Groovy/Spock,这次使用GMavenplus插件,更加方便. 具体步骤 1. 导入Spock和Groovy依赖 <dependency> ...

  5. SpringCloud升级之路2020.0.x版-40. spock 单元测试封装的 WebClient(下)

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 我们继续上一节,继续使用 spock 测试我们自己封装的 WebClient 测试针对 r ...

  6. 人生苦短?试试Groovy进行单元测试

    如果您今天正在编程,那么您很可能听说过单元测试或测试驱动的开发过程.我还没有遇到一个既没有听说过又没有听说过单元测试并不重要的程序员.在随意的讨论中,大多数程序员似乎认为单元测试非常重要. 但是,当我 ...

  7. SpringCloud升级之路2020.0.x版-40. spock 单元测试封装的 WebClient(上)

    本系列代码地址:https://github.com/JoJoTec/spring-cloud-parent 我们来测试下前面封装好的 WebClient,这里开始,我们使用 spock 编写 gro ...

  8. Groovy Spock环境的安装

    听说spock是一个加强版的Junit,今天特地安装了,再把过程给大家分享一下. 首先说明,我的Java项目是用maven管理的. 我用的Eclipse是Kelper,开普勒. 要使用Spock之前, ...

  9. [每日一学]apache camel|BDD方式开发apache camel|Groovy|Spock

    开发apache camel应用,最好的方式就是tdd,因为camel的每个组件都是相互独立并可测试的. 现在有很多好的测试框架,用groovy的Spock框架的BDD(行为测试驱动)是比较优秀和好用 ...

随机推荐

  1. 判断字符串是否为ip地址----python

    def isIp(ip_str): flag = True if '.' not in ip_str: return False if ip_str.count('.')!=3 : return Fa ...

  2. 解决ionic5多个模态关闭一个其他不显示的问题

    ionic5 modal使用过程中,在模态窗中打开另外一个模态窗,浏览器中显示正常,但是andorid8系统真机调试时,关闭最上层模态窗,上级模态窗DOM中存在,但是不显示. 原因是android版本 ...

  3. Django基础011-form&modelform

    1.form from django import forms from django.core.exceptions import ValidationError #出现异常时用的 from use ...

  4. Django基础009--Paginator分页

    1.引入 from django.core.paginator import Paginator 2.Paginator对象提供的方法 articles = models.Article.object ...

  5. Linux groupadd and groupmod

    groupadd [选项] group 三个参数: -g,--gid 指定组gid,除非使用-o,否则gid必须时唯一的 -o,--non-unique 允许创建有重复gid的组 -r, --syst ...

  6. urllib库中的URL编码解码和GETPOST请求

    在urllib库的使用过程中,会在请求发送之前按照发送请求的方式进行编码处理,来使得传递的参数更加的安全,也更加符合模拟浏览器发送请求的形式.这就需要用urllib中的parse模块.parse的使用 ...

  7. PLICP

    介绍 PLICP相比较于普通ICP算法,使用点线之间的距离作为度量,最终找到一个最小化该度量的闭式解(解析解). 最优结果以平方的速度收敛.相比较于ICP,IDC,MBICP.PLICP更加准确,且需 ...

  8. PO封装设计模式 -- App移动端测试

    前言: 一.App_Po 封装 (用互联网上随便一个app进行) base 存放的是页面基础类,后续的类需继承基础类 common 存放的是公共部分,测试固件分离部分,新增截图功能部分 Data 存放 ...

  9. 微信小程序云开发-云存储-上传单个视频到云存储并显示到页面上

    一.wxml文件 <!-- 上传视频到云存储 --> <button bindtap="chooseVideo" type="primary" ...

  10. 《PHP 实现 Base64 编码/解码》笔记

    前言 早在去年 11 月底就已经看过<PHP 实现 Base64 编码/解码>这篇文章了,由于当时所掌握的位运算知识过于薄弱,所以就算是看过几遍也是囫囵吞枣一般,不出几日便忘记了其滋味. ...