zoukankan      html  css  js  c++  java
  • Cucumber 行为驱动开发简介

    Cucumber 是一个能够理解用普通语言 描述的测试用例的支持行为驱动开发(BDD)的自动化测试工具,用Ruby编写,支持Java和.Net等多种开发语言。

    现在看看Cucumber中用到的术语 。

    在Cucumber中,每个用例用一个feature表示 ,其基本格式如下:
    Feature: 描述 
      <story> 

      <scenario 1> 
      ... 
      <scenario N> 

    其中,story对feature进行描述 ,其常用格式如下:
    In order <目的> 
    As a <角色> 
    I want <功能描述> 
    So that <商业价值> 

    每个feature可由若干个scenario 构成,用以描述系统的行为 ,其常用格式如下:
    Scenario Outline: 描述 
      Given <条件> 
      When <事件> 
      Then <结果> 
    如果有多个条件等,可以用关键字And或But进行连接。每个步骤中,可选参数用"<>"标识。

    scenario中的每个步骤都需要被定义 ,其格式如下:
    关键字 /正则表达式/ do |参数名| 
      代码 
    end 
    这里 的参数来自于正则表达式,均为字符串类型。


    下面看看如何用Cucumber进行开发 (参考自这个 例子)。

    首先编写feature ,并保存为feature/addition.feature文件:

    Feature: Addition
      In order to avoid silly mistakes
      As a math idiot
      I want to be told the sum of two numbers
     
      Scenario Outline: Add two numbers
        Given I have entered <input_1> into the calculator
        And I have entered <input_2> into the calculator
        When I press <button>
        Then the result should be <output> on the screen
     
      Examples:
        | input_1 | input_2 | button | output |
        | 20 | 30 | add | 50 |

    然后用Ruby语言定义scenario中的每个步骤 ,并保存为features/step_definitions/addition.rb文件:

    [ruby] view plain copy
     
    1. Given /I have entered (/d+) into the calculator/ do |n|  
    2.   @calc = Calculator.new  
    3.   @calc.push n.to_i  
    4. end  
    5. When /I press (/w+)/ do |op|  
    6.   @result = @calc.send op  
    7. end  
    8. Then /the result should be (.*) on the screen/ do |result|  
    9.   @result.should == result.to_f  
    10. end   



    最后编写相应代码 :

    [ruby] view plain copy
     
    1. class Calculator  
    2.   def push(n)  
    3.     @args ||= []  
    4.     @args << n  
    5.   end  
    6.    
    7.   def add  
    8.     @args.inject(0){|n,sum| sum+=n}  
    9.   end  
    10. end   



    进行测试 :
    cucumber feature/addition.feature 

    如果得到类似于以下的结果,则表明代码无误:
    1 scenario (1 passed) 
    4 steps (4 passed) 
    0m0.009s 

    否则,会得到红色提示,则需要修改相应代码。

  • 相关阅读:
    [转][黄忠成]Object Builder Application Block (1)
    C#.NET里面抽象类和接口有什么区别
    MVC中AOP思想的体现(四种过滤器)并结合项目案例说明过滤器的实际用法
    NHibernate之(24):探索NHibernate二级缓存(下)
    使用 ES (elasticsearch) 搜索中文
    elasticsearch 中文 term & completion suggester
    uwsgs loading shared libraries: libicui18n.so.58 异常处理
    tensorflow with gpu 环境配置
    Java 多线程执行
    SpringBoot log4j2 异常
  • 原文地址:https://www.cnblogs.com/yuanchunli/p/5477646.html
Copyright © 2011-2022 走看看