代码之家  ›  专栏  ›  技术社区  ›  Simon Keep

在SpecFlow中,如何在步骤/功能之间共享数据?

  •  32
  • Simon Keep  · 技术社区  · 16 年前

    我有两个特性,它们使用一个通用的“when”步骤,但在不同的类中有不同的“then”步骤。

    例如,我如何访问我的MVC控制器调用的ActionResult在我的两个然后的步骤中的when步骤中?

    5 回复  |  直到 7 年前
        1
  •  33
  •   Simon Keep    10 年前

    在SpecFlow 1.3中,有三种方法:

    1. 静态成员
    2. 情景语境
    3. 上下文注入

    评论:

    1. 静态成员非常务实,在这种情况下不像开发人员最初想象的那样邪恶(在步骤定义中不需要线程或模拟/替换)

    2. 查看@si的答案保持在这个线程中

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

        2
  •  33
  •   Ralph Willgoss    13 年前

    使用scenarioContext类,该类是所有步骤都通用的字典。

    ScenarioContext.Current.Add("ActionResult", actionResult);
    var actionResult = (ActionResult) ScenarioContext.Current["ActionResult"];
    
        3
  •  15
  •   mcintyre321    7 年前

    我有一个助手类可以让我写

    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; }
         }
     }
    

    2019年编辑:我现在会用@joet的答案,看起来你不需要定义扩展就可以获得同样的好处。

        4
  •  8
  •   JoeT    8 年前

    我不喜欢使用scenario.context,因为需要逐条列出每个字典条目。我找到了另一种方法来存储和检索物品,而不需要铸造它。但是,这里有一个折衷,因为您有效地使用类型作为键,从scenarioContext字典访问对象。这意味着只能存储该类型的一个项。

    TestPage testPageIn = new TestPage(_driver);
    ScenarioContext.Current.Set<TestPage>(testPageIn);
    var testPageOut = ScenarioContext.Current.Get<TestPage>();
    
        5
  •  0
  •   Daniel Kereama    8 年前

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

    ...
    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 
    

    您可以将实际值存储在字典、属性包或类似文件中。

    推荐文章