代码改变世界

初识gauge自动化测试框架(二)

2018-10-23 23:31  虫师  阅读(5947)  评论(1编辑  收藏  举报

看到一些同学对该工具有点一兴趣,那么我将继续介绍Gauge自动化测试工具。

Gauge本质上一个BDD(Behavior Driven Development)测试框架。所以,首先你要了解BDD的操作方式。

BDD包含两部分,一部分是: 软件行为描述。另一部分是: 针对描述编写测试代码

首先,行为描述文件描述如下。

# 计算器

我想实现一个简单的计算器,这个计算器可以做两个数的加、减、乘、除运算。
 
## 测试加法
 
* 创建Calculator类。
* 相使用add方法,计算3 加5 的结果为8。

创建一个行为文件specs/calculator.spec,将上面的内容翻译一下:

# Calculator

I'm implementing a simple calculator that can add, 
subtract, multiply, and divide two numbers.


## Test addition

* Create a Class Calculator.

* Using Add method, digital "3" plus "5" result is "8".

唯一和其它BDD框架不同之处在于,Guage的行为描述文件是由markdown话法编写。
比如Python的BDD框架behave是由一些关键字组成(Feature、Scenario、Given、When、Then等)。

# -- FILE: features/example.feature
Feature: Showing off behave  
 
 Scenario: Run a simple test    
    Given we have behave installed     
      When we implement 5 tests
    Then behave will test them for us!

好了,我上面用markdown写的行为文件我想你是可以看懂的,如果实在不懂markdown语法的话。也许这个在线工具可以帮你快速学习:

http://mahua.jser.me/

再接下来,针对行为文件来写代码实现。创建 setp_impl/calculator.py 文件。

from getgauge.python import step


@step("Create a Class Calculator.")
def create_Calculator():
    calc = Calculator()


@step("Using Add method, digital <a> plus <b> result is <c>.")
def test_add(a, b, c):
    calc = Calculator()
    result = calc.add(a, b)
    assert result == int(c)


class Calculator():

    def add(self, x, y):
        return int(x) + int(y)

在实现测试代码文件中,通过 @step() 装饰器引用行为描述文件中的步骤,并将其中用到的数据通过 <变量> 替换,将变量用到测试步骤中。

严格来说,Calculator() 类的实现应该单独文件中实现,这里只是为了省事儿。

在项目根目录下运行 gauge run specs命令。

查看测试报告。

如果我想增加测试用例呢? 很简单,只需要增加行为描述即可。

……

## Test addition big number

* Create a Class Calculator.

* Using Add method, digital "301" plus "578" result is "879".

那么问题来了,gauge到底可以用来做什么类型的测试,这里有一些例子供你参考。
https://getgauge-examples.github.io/

Web Page Counters
Computer Desks