6

我从 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 时,我不断收到异常?参数。我检查了正则表达式,它肯定会按预期解析场景。我知道我可以像方法重载等这样粗略的东西,我只是想知道 SpecFlow 是否支持默认参数值的想法,或者确实是另一种实现相同效果的方法。

非常感谢

4

4 回答 4

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 参数,其余的由 SpecFlow 完成...

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

您可以在https://github.com/techtalk/SpecFlow/wiki/Step-Argument-Conversions看到更多示例

于 2011-02-26T20:35:36.853 回答
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 妥协可能无济于事。

于 2011-02-07T17:09:04.140 回答
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
}

于 2011-02-07T14:55:53.093 回答
0

到目前为止,我想出的最好的方法如下: 这比我原来的建议要干净得多,但仍然需要我手动检查参数。注意方法中的字符串参数。既不是 Int 也不是 Int?在上述定义的场景中工作。
[Given(@"myfield equals todays date(?: ([\+-]\d+) days)?")]
public void MyfieldEqualsTodaysDate(string days)
{
int modifer = 0;
if(!String.IsNullOrEmpty(days))
{
modifer = Int32.Parse(days)
}
}

于 2011-02-07T15:50:42.227 回答