4

BDD(7):使用Transform讓稅金同時支援5%和0.05表達方式

 2 years ago
source link: http://teddy-chen-tw.blogspot.com/2017/02/bdd7transform5005.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

BDD(7):使用Transform讓稅金同時支援5%和0.05表達方式

Feb. 21 22:00~00:00

▲好亂的程式碼XD

問題描述

今天延續昨天的例子,討論Cucumber的Transform功能。在昨天的範例中我們用「0.05」的格式來表達營業稅:

Given The VAT rate is 0.05

相對應的step definition為:

Given("^The VAT rate is (\\d+\\.\\d+)$", (Double arg1) –> {

如果有人想要用%的方式來表示營業稅:

Given The VAT rate is 5%

那麼相對應的相對應的step definition變成:

Given("^The VAT rate is (\\d+)%$", (Integer arg1) –> {

Given("^The VAT rate is (\\d+%)$", (String arg1) –> {

對撰寫scenario的人來說,用0.05或5%來代表營業稅都是一樣的意思,如果需要兩條不同的step definition來表示相同的東西,感覺有點怪怪的。怎麼辦?

使用 Or

我們可以使用regular expression的「|」符號來讓一個step definition同時對應「0.05」與「5%」:

▼以下scenario例子故意重複撰寫兩次「The VAT rate is」,第一次使用0.05,第二次使用5%。

▼這個step definition可以同時對應到以上兩種情況。

Given("^The VAT rate is (\\d+\\.\\d+|\\d+%)$", (String arg1) -> {
    System.out.println("arg1 = " + arg1);
});

▼輸出結果為:

arg1 = 0.05
arg1 = 5%

但是這樣問題只解決了一半,因為我們希望營業稅可以用以下方式指定給Invoice物件:

invoice.setVATRate(arg1);

現在營業稅的資料型態變成String,應該想辦法轉成double或其他資料型態,這樣之後要進行數字運算比較方便。

▼Cucumber的Transform功能可以協助解決這個問題,首先我們新增Percentage(百分比)類別,它可以接受0.05或5%這種格式,然後轉成double型態。

▼接著新增PercentageTransformer類別,它必須繼承自Cucumber的Transformer類別,然後覆寫transform method,以便把一個字串轉成Percentage類別。

▼到這裡準備工作都已就緒,最後只要把step definition改一下,從原本傳入參數接受String型別改成接受Percentage型別,然後在它前面加上@Transform(PercentageTransformer.class)告訴Cucumber如何把step裡面的字串(也就是0.05或5%)透過PercentageTransformer類別轉成Percentage型別傳入。

▼輸出結果為:

arg1 data = 0.05
arg1 = 0.05
arg1 data = 5%
arg1 = 0.05

現在我們的scenario可以同時支援「Given The VAT rate is 0.05」與「Given The VAT rate is 5%」了。

友藏內心獨白:自動轉換型別還挺方便的。

延伸閱讀


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK