是否可以在beforeFeature Hook中使用变量作为Specflow场景声明的一部分?

时间:2017-05-03 08:55:13

标签: c# hook specflow

我是Specflow的新手,我正在尝试使用Specflow BeforeFeature Hook查看是否可行。我有一些动态测试数据设置,仅适用于特定功能。我想将这些测试数据值用作场景测试的一部分。这是功能文件的场景测试之一:

@logintest
Feature: User login
Scenario: User login with different product access
Given I am in <productType> login page
When I login as <user>
I should see <productType> logo in my account

在BeforeFeature()中,我们有生成的函数:   - 具有产品访问类型属性的随机用户帐户   - 产品登录页面的随机网址。 (例如:productA234234.dev.local)

[Binding]
public class LoginHooks
{
    [BeforeFeature("logintest")]
    public static void BeforeFeature()
    {
        UserAccount testUser = new UserAccount(productType1);
        var product1Url = CreateProductUrl(productType1);
        FeatureContext.Current.Set("testUser", testUser);
        FeatureContext.Current.Set("productUrl", productUrl);
        ...
    }

因为每次运行测试时都会随机生成用户名,所以我无法将Gherkins的用户名作为数据表等的一部分提供。有没有办法构建Gherkins以从FeatureContext中获取值?< / p>

[Binding]
public class UserLoginSteps
{
   //var productUrl = ???
   [Given(@"I am in (.*) login page")]
   public void GivenIAmInLoginPage(string productUrl)
   { . . .}
}

问题:

  1. 是否可以获取productUrl的FeatureContext值并在步骤中设置?
  2. 我认为在这种情况下正则表达式是不正确的。是否有另一种方法来构造它以将变量作为数据输入的一部分?
  3. 谢谢!

1 个答案:

答案 0 :(得分:1)

当您使用BDD时使用随机数据是一种不好的方法AFAK 所以我认为你需要将你的功能改为这样的

  @alogintest
Feature: SpecFlowFeature1
    try many user logins 

Scenario Outline:  User login with different product access
Given I am in <productType> login page
And  the user is <user>
When I login 
Then I should see <prouctResult> logo in my account
Examples:  
| productType | userAccount | userPwd | productTypeResult |
| P1          | u1          | pwd1    | p1                |
| P2          | u2          | pwd2    | p2                |

is it possible to get FeatureContext values for the productUrl and set in the step? 是的,您可以为每个特定的productTypeUrl添加一列,例如

注意 that you can add as many as you want scenarios

I think the regex Given is incorrect in such case. Is there another way to construct it to take a variable as part of the data input?

是的,因为占位符仅用于Scenario Outlines

此处生成了您的步骤

using TechTalk.SpecFlow;

namespace loginTest
{
    [Binding]
    public class SpecFlowFeature1Steps
    {
        [Given(@"I am in P(.*) login page")]
        public void GivenIAmInPLoginPage(int p0)
        {
            ScenarioContext.Current.Pending();
        }

        [Given(@"the user is (.*)")]
        public void GivenTheUserIs(string p0)
        {
            ScenarioContext.Current.Pending();
        }

        [When(@"I login")]
        public void WhenILogin()
        {
            ScenarioContext.Current.Pending();
        }

        [Then(@"I should see (.*) logo in my account")]
        public void ThenIShouldSeeLogoInMyAccount(string p0)
        {
            ScenarioContext.Current.Pending();
        }
    }
}