2010-05-21 83 views

回答

31

在SpecFlow 1.3有三种方法:

  1. 静态成员
  2. ScenarioContext
  3. ContextInjection

评论:

  1. 静态成员都非常务实,在这种情况下不那么邪恶,因为我们的开发人员可能会首先想到(没有螺纹或需要嘲讽/升压型定义更换)

  2. 从@Si

    查看答案请将本线程

  3. 如果步骤定义类的构造函数需要参数,Specflow将尝试注入这些参数。这可以用于将相同的上下文注入到多个步骤定义中。
    在这里看到一个例子: https://github.com/techtalk/SpecFlow/wiki/Context-Injection

+2

我认为也可以使用实例变量,如其中的一个例子:http://github.com/techtalk/SpecFlow-Examples/blob/主/ BowlingKata/BowlingKata-NUnit的/ Bowling.Specflow/BowlingSteps。cs – 2010-07-14 14:59:03

+0

@Carl:实例变量可用于在同一个类中实现的stepdefinition之间共享数据。但问题是关于不同阶级的实施。 – jbandi 2012-01-30 11:44:10

+0

ScenarioContext对静态成员的优点是可以将状态与其他测试类共享,因此.feature文件可以自由编辑。本页面介绍了三种合理的方法:https://blog.markvincze.com/how-to-store-state-during-specflow-tests/ – 2017-05-23 10:06:07

28

使用ScenarioContext类,它是所有步骤都通用的字典。

ScenarioContext.Current.Add("ActionResult", actionResult); 
var actionResult = (ActionResult) ScenarioContext.Current["ActionResult"]; 
+2

这是可怕的使用:( – 2012-06-22 12:25:16

+2

为什么你们说,这是可怕的上校? – Turnkey 2012-11-26 20:11:31

+0

老实说,我不喜欢它 – Jupaol 2013-04-03 22:19:08

13

我有一个辅助类,它可以让我写

Current<Page>.Value = pageObject; 

这是在ScenarioContext的包装。它的工作原理断类型名称,所以它需要延长一点,如果你需要访问同类型

public static class Current<T> where T : class 
{ 
    internal static T Value 
    { 
     get { 
       return ScenarioContext.Current.ContainsKey(typeof(T).FullName) 
       ? ScenarioContext.Current[typeof(T).FullName] as T : null; 
      } 
     set { ScenarioContext.Current[typeof(T).FullName] = value; } 
    } 
} 
5

我讨厌,因为需要对铸造出每个字典词条Scenario.Context的两个变量。但后来发现内置的功能自动处理所有这些。只有当该类型的一个实例被存储时才有效。

TestPage testPageIn = new TestPage(_driver); 
ScenarioContext.Current.Set<TestPage>(testPageIn); 
var testPageOut = ScenarioContext.Current.Get<TestPage>(); 
0

您可以在您的步骤中定义一个参数,这是您要存储的值的关键。通过这种方式,您可以通过使用该键在以后的步骤中引用它。

... 
Then I remember the ticket number '<MyKey>' 
.... 
When I type my ticket number '<MyKey>' into the search box 
Then I should see my ticket number '<MyKey>' in the results 

您可以将实际值存储在字典或物业包或类似物中。