美文网首页
spock测试Data Driven Testing

spock测试Data Driven Testing

作者: 风雨断肠 | 来源:发表于2017-07-25 22:47 被阅读0次

    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
    作者水平有限,出现错误请您指正,谢谢。

    相关文章

      网友评论

          本文标题:spock测试Data Driven Testing

          本文链接:https://www.haomeiwen.com/subject/imvgkxtx.html