在上一次Spock实践中我们介绍了Spock的基本概念,今天我们继续介Spock的数据驱动和一些技巧。
一、首先介绍下spock中的数据驱动:
Spock框架支持多种数据驱动方式
1.数据表,强于可读性,适合数据量小的场景
2.数据管道,强于可维护性,适合数据量多的场景
步骤:
a. 在用例中,把可变的变量参数化
b. 在where模块中配置参数数据
在实际测试工作中,往往测试数量较大,此时最佳实践方式是从数据库读取数据作为驱动数据,例如:
二、技巧
1.对象构建技巧
在测试过程中,需要构建测试数据对象,对于比较复杂属性的对象构造,用java往往比较繁琐笨重,需要不断调用setter方法设置属性值,但是groovy语法可以基于map的构造器构造对象,能节省很多的代码。
通过groovy的object.with结构可以分组对象参数,例如
def "冒烟测试"() {
given:"discount coupon param"
def stairList = [] 1.upto(3, { stairList<< new CouponStair(quota: 1000 * it, discount: 0.9 - 0.1 * it)}) baseCoupon = newCoupon() baseCoupon.with { setStyle(3) setMaxDiscount(2000) setStairs(stairList) setGrantType(grantType) }
when:"execute create coupon"
def createCoupon =couponWriteService.createCoupon(clientInfo, baseCoupon, null)
then:"check the create result"
createCoupon
println(createCoupon)
where:"grantType is below"
grantType<< [1, 2, 3, 5]
}
2.集合操作技巧
l each()方法-遍历集合,闭包应用于每个元素
def "打印批次信息"() { def coupons =(100101435..100101440).collect { couponId -> couponReadService.getByCouponId(clientInfo,00001, couponId) } expect: coupons coupons.each {coupon -> println " }
l any()方法-遍历集合,若至少一个元素满足闭包条件,返回true,否则返回false
promotionSummaryList.empty ?: promotionSummaryList.any { it.promotionType == 3 && it.promotionSubType == 302 }
l every()方法-遍历集合,若每个元素都满足闭包条件,返回true,否则false
def "demo every"() { expect: (1..10).every {it > 0 }
l find()方法 找到集合中第一个符合条件的元素并返回该元素,未找到则返回null 2 == (1..10).find { i -> i % 2== 0 }
l findAll()方法 遍历集合并返回符合条件的元素集合。
[2, 4, 6, 8, 10] ==(1..10).findAll { i -> i % 2 == 0 }
l collect()方法 集合中的元素根据条件转化为新的元素并返回一个新元素集合。
[1, 8, 27] == (1..3).collect { i -> i**3 }
l list.elesFild()直接返回元素指定字段组成列表。
def "demo 列表直接返回元素相关属性列表"() { PromotionSkuQueryquery = new PromotionSkuQuery(venderId: 20361, promoId: 1000372401) def promotionSkuList =promotionReadInnerService.getPromotionSkuList(new ClientInfo(appName:"marketCenter"), query) def skuIds =promotionSkuList.skuId expect: skuIds instanceof List println skuIds }
列表元素去重 def "两种方法,列表元素去重"() { def x = [1,1,1] expect: assert [1] == newHashSet(x).toList() assert [1] == x.unique() } def "列表去null"() { def x = [1,null,1] expect: assert [1,1] == x.findAll{it!= null} assert [1,1] == x.grep{it} }
本文分享自微信公众号 - 搜狗测试(SogouQA),作者:Eason
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2020-09-04
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句