2010-05-21 139 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 

您可以將實際值存儲在字典或物業包或類似物中。