2016-10-03 45 views
2

我正在使用SpecFlow測試一個類MortgageCalculator。我發現我有兩種設置步驟文件的方法,一種是我有一個類級別的MortgageCalculator,另一種是我使用ScenarioContext(參見下文)。哪個更好?在SpecFlow中,我應該使用類字段還是ScenarioContext作爲我正在測試的對象?

我發現選項1要容易得多,因爲我不必繼續獲取並設置ScenarioContext。但我被教導使用ScenarioContext。

選項1:

[Binding] 
public sealed class MortgageCalculatorSteps 
{ 
    private MortgageCalculator calculator; 

    [Given(@"I have a MortgageCalculator")] 
    public void GivenIHaveAMortgageCalculator() 
    { 
     calculator = new MortgageCalculator(); 
    } 

    [Then(@"I can do something with the calculator")] 
    public void ThenICanDoSomethingWithTheCalculator() 
    { 
     calculator.DoSomething(); 
    } 
} 

選項2:

[Binding] 
public sealed class MortgageCalculatorSteps 
{ 
    [Given(@"I have a MortgageCalculator")] 
    public void GivenIHaveAMortgageCalculator() 
    { 
     var calculator = new MortgageCalculator(); 
     ScenarioContext.Current.Set(calculator); 
    } 

    [Then(@"I can do something with the calculator")] 
    public void ThenICanDoSomethingWithTheCalculator() 
    { 
     var calculator = ScenarioContext.Current.Get<MortgageCalcualtor>(); 
     calculator.DoSomething(); 
    } 
} 

回答

2

在我看來,你所概述的選項都沒有最好的解決方案。正如Andreas在其他答案中指出的,最好的選擇是使用ContextInjection。爲什麼?

  • 廠當測試並行運行,這利用ScenarioContext.Current不會
  • 允許含有步驟不同的類別,這反過來又可以讓你喲組織在任何你想要你的步驟和之間共享數據避免了含有多種步法非常大的類
  • 允許你的數據是強類型
  • 允許在合適的粘性類收集你的數據,每個保持單一職責原則

我們往往稱這些類爲背景,讓我在你的情況選擇是要做到這一點,大概是:

[Binding] 
public sealed class MortgageCalculatorSteps 
{ 
    private MortgageCalculatorContext calculatorContext; 

    public MortgageCalculatorSteps(MortgageCalculatorContext calculatorContext) 
    { 
     this.calculatorContext=calculatorContext; 
    } 

    [Given(@"I have a MortgageCalculator")] 
    public void GivenIHaveAMortgageCalculator() 
    { 
     calculatorContext.Calculator = new MortgageCalculator(); 
     // or you could do something like: calculator.InitialiseCalculator() 
    } 

    [Then(@"I can do something with the calculator")] 
    public void ThenICanDoSomethingWithTheCalculator() 
    { 
     calculatorContext.Calculator.DoSomething(); 
    } 
} 

的好處可能不是這樣一個簡單的例子是顯而易見的,但在我的經驗,這從長遠來看,讓你的生活變得更加簡單。

相關問題