初識gauge自動化測試框架(二)
看到一些同學對該工具有點一興趣,那麼我將繼續介紹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/