spock测试Data Driven Testing

spock测试框架,引用官方文档的描述:
Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers. Spock is inspired from JUnit, jMock, RSpec, Groovy, Scala, Vulcans, and other fascinating life forms.

这篇文章主要是简单介绍了spock的Data Driven Testing

数据启动测试:

通常,多次运行相同的测试代码,具有不同的输入和预期结果是有用的

example:

  class MathSpec extends Specification {
        def "maximum of two numbers"() {
        expect:
            // exercise math method for a few different inputs
            Math.max(1, 3) == 3
            Math.max(7, 4) == 7
            Math.max(0, 0) == 0
          }
    }

这个例子的写法简单,但是存在一些缺点:
代码和数据混合,不能轻易地独立更改

  1. 数据不能自动生成或从外部来源获取
  2. 为了多次运行相同的代码,必须将其复制或提取为单独的方法
  3. 如果发生故障,可能不会立即清楚哪些输入导致故障
  4. 多次执行相同的代码不会像执行单独的方法那样受益于相同的隔离

Spock的数据驱动测试

数据测试驱动解决了这个问题,首先引入了三个数据变量

 class MathSpec extends Specification {
      def "maximum of two numbers"(int a, int b, int c) {
      expect:
      Math.max(a, b) == c
      ...
      }
  }

在完成逻辑的测试部分,我们还需要提供相应的数据,这些工作则是在 where: 保存相应的数据块。

databales

固定数据集,

class MathSpec extends Specification {
    def "maximum of two numbers"(int a, int b, int c) {
        expect:
                Math.max(a, b) == c

        where:
              a | b | c
              1 | 3 | 3
              7 | 4 | 7
              0 | 0 | 0
       }
}

表的第一行声明了数据变量,表的后续行,保存了相应的值。对于其中的每一行,feature method 将都执行一次,称之为方法的迭代。

Tips
数据表必须至少有两列。单列表可以写成:

where:
  a | _ 
  1 | _ 
  7 | _ 
  0 | _

Method Unrolling
@Unroll

spock里的一个注解:
A method annotated with @Unroll will have its iterations reported independently:
有@Unroll的方法对每一个迭代都有自己的独立报告。

example:

   @Unroll
   def "maximum of two numbers"() {
   ...
  }


maximum of two numbers[0]   PASSED
maximum of two numbers[1]   FAILED

Math.max(a, b) == c
|        |  |  |  |
|        7  4  |  7
42           false
maximum of two numbers[2]   PASSED

This tells us that the second iteration (with index 1) failed.

资料来源:spock doc:
http://spockframework.org/spock/docs/1.1/data_driven_testing.html
作者水平有限,出现错误请您指正,谢谢。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,026评论 19 139
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,590评论 2 45
  • 第一天,生活还是如此美好
    社情启示录阅读 252评论 0 1
  • 看完《罗马蒂克消亡史》,我被剧情带进去了,仿佛身上也具有了深沉的气质,不想漏丝毫的感情,淡淡的感受着这个世界,...
    未央行者阅读 721评论 0 0
  • The Qinhuai River By Chou Yi Tr. Qin Dachuan I order a di...
    诗人丑乙阅读 377评论 0 0