为SpecFlow Scenario提供多个When语句

时间:2013-11-05 10:49:18

标签: c# params specflow

SpecFlow相当新,请耐心等待。

我正在与同事合作,以便对使用SpecFlow可以做些什么有基本的了解。

我们使用的是经典的FizzBu​​zz问题,我们用它来测试单元测试,以比较我们在SpecFlow中如何处理类似问题。

我们按照以下方式编写了我们的场景:根据需要增加代码:

(请原谅命名只是想让测试结束)

Scenario: 1 is 1
    Given there is a FizzBuzzFactory
    When you ask What I Am with the value of 1
    Then the answer should be 1 on the screen

Scenario: 3 is Fizz
    Given there is a FizzBuzzFactory
    When you ask What I Am with the value of 3
    Then the answer should be Fizz on the screen

Scenario: 5 is Buzz
    Given there is a FizzBuzzFactory
    When you ask What I Am with the value of 5
    Then the answer should be Buzz on the screen

Scenario: 15 is FizzBuzz
    Given there is a FizzBuzzFactory
    When you ask What I Am with the value of 15
    Then the answer should be FizzBuzz on the screen

这导致了开发一种计算某些数字总和的方法

我们写的场景是:

Scenario: Sumof 1 + 2 + 3 is Fizz
    Given there is a FizzBuzzFactory
    When you add the sum of 1
    When you add the sum of 2
    When you add the sum of 3
    Then the answer should be Fizz on the screen

我们写的方法一次接受一个数字然后总结。

理想情况下,我会提供:

Scenario: Sumof 1 + 2 + 3 in one go is Fizz
    Given there is a FizzBuzzFactory
    When you add the sum of 1,2,3
    Then the answer should be Fizz on the screen

如何设置语句,以便在方法签名上获得params int[]

1 个答案:

答案 0 :(得分:10)

如果您使用StepArgumentTransformation,那么specflow步骤绑定可以很好地支持您的问题。这就是我喜欢specflow的原因。

[When(@"you add the sum of (.*)")]
public void WhenYouAddTheSumOf(int[] p1)
{
    ScenarioContext.Current.Pending();
}

[StepArgumentTransformation(@"(\d+(?:,\d+)*)")]
public int[] IntArray(string intCsv)
{
    return intCsv.Split(',').Select(int.Parse).ToArray();
}

此处的StepArgumentTransformation允许您从现在开始在任何步骤定义中使用任何逗号分隔的整数列表,并将其作为Array参数接受。

如果你想玩StepArgumentTransformations,那么值得学习一些正则表达式,以使它们变得美观和具体。注意我在绑定时也可以使用(\d+(?:,\d+)*)而不是.*