2011-02-07 108 views
6

我開始在SpecFlow的世界,我遇到了我的第一個問題。 在保持我的代碼乾的方面,我想做到以下幾點:默認值Specflow步驟定義

有兩種情況:

Given I am on a product page
And myfield equals todays date
Then...

Given I am on a product page
And myfield equals todays date plus 4 days
Then...

我希望使用以下步驟定義覆蓋我的And子句的兩種變體:

[Given(@"myfield equals todays date(?: (plus|minus) (\d+) days)?")]
public void MyfieldEqualsTodaysDate(string direction, int? days)
{
//do stuff
}

但是,當SpecFlow試圖解析int時,我不斷收到異常? PARAM。 我檢查了正則表達式,它肯定會按預期解析場景。 我知道我可以像方法重載等粗糙的東西,我只是想知道,如果SpecFlow支持的默認參數值的想法,或實際上另一種方式來實現相同的效果。

非常感謝

回答

8

的默認值(還),但對於你的具體情況,我可以建議如下:

SpecFlow支持創建「一步說法轉變」。有了它們,你可以創建不同的模式日期時間解析方法:

[StepArgumentTransformation("todays date")] 
public DateTime TransformToday() 
{ 
    return DateTime.Today; 
} 
[StepArgumentTransformation("todays date (plus|minus) (\d+) days")] 
public DateTime TransformOtherDay(string direction, int days) 
{ 
    //... 
} 

在此之後,你只需要在你的步驟,使用一個DateTime PARAM,其餘由SpecFlow做...

[Given(@"myfield equals (.*)")] 
public void MyfieldEqualsTodaysDate(DateTime date) 
{ 
    //do stuff 
} 

你可以在https://github.com/techtalk/SpecFlow/wiki/Step-Argument-Conversions

2

我的一個朋友使用以下方法

Given I am on a product page And myfield equals {TODAY}

Given I am on a product page And myfield equals {TODAY+4}

然後,您可以解析特殊用語,在步驟DEFS

[Given(@"myfield equals ("SOME MATCHING REGEX")]
public void MyfieldEqualsTodaysDate(string date) {
//parse TODAY or you could use TOMORROW you get the idea
}

+0

看到更多的例子我喜歡這個主意,以增加自己的日期表達式放在常見方案(今天,明天,下個月等) – 2011-02-07 15:53:28

0

,我所管理的最好拿出到目前爲止是這樣的:
[Given(@"myfield equals todays date(?: ([\+-]\d+) days)?")]
public void MyfieldEqualsTodaysDate(string days)
{
int modifer = 0;
if(!String.IsNullOrEmpty(days))
{
modifer = Int32.Parse(days)
}
}

這是比我原來的建議,更清潔,但仍然需要我手動檢查參數。請注意方法中的字符串參數。既不是Int也不是Int?在上面定義的場景中工作。

2

您的步驟看起來在相當以開發人員爲中心的語言中表達過。

如果你用利益相關者的語言來描述他們會發生什麼?

Given I am on the product page 
And my product is due for delivery today 

Given I am on the product page 
And my product is due for delivery in 4 days 

Given I am on the product page 
And my product was due for delivery 3 days ago 

現在您可以使用正則表達式匹配這些不同的步驟,並刪除較低級別的重複。

[Given(@"my product is due for delivery today")] 
public void GivenTheProductIsDueToday() { 
    var dueDate = Date.Today; 
    DoOtherStuffWith(dueDate); 
} 

[Given(@"my product is due for delivery in (.*) days")] 
public void GivenTheProductIsDueIn(int days) { 
    var dueDate = Date.Today.AddDays(days); 
    DoOtherStuffWith(dueDate); 
} 

[Given(@"my product was due for delivery (.*) days ago")] 
public void GivenTheProductWasDue(int days) { 
    var dueDate = Date.Today.AddDays(-1*days); 
    DoOtherStuffWith(dueDate); 
} 

我不使用SpecFlow,但是我希望這是有道理的。 BDD的重點更多的是關於企業和利益相關者之間的對話,而不是關於測試或自動化。從長遠來看,妥協對於DRY來說可能沒有幫助。不支持

+0

爲什麼「GivenTheProductIsDueToday(字符串日期業務方面的事情)「的日期已過在所有? – 2011-05-10 09:32:19

+0

糟糕!沒有理由,除了我的人爲錯誤。 – Lunivore 2011-05-10 14:02:15