看到一些同學對該工具有點一興趣,那么我將繼續介紹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語法的話。也許這個在線工具可以幫你快速學習:
再接下來,針對行為文件來寫代碼實現。創建 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/