2

Anyone using SpecFlow will likely have come across Context Injection and Scenario Context for storing data across different binding classes. (For more detail see: https://specflow.org/documentation/Sharing-Data-between-Bindings/)

As a Developer, the Scenario Context just seems very brittle compared with the Context Injection. You use strings to save and retrieve data and it is basically a global variable system, which to me normally seems wrong. The dependency injection, on the other hand, works nicely with different classes being able to be created to store different types of data.

Can anyone see a reason why you would want to use Scenario Context over Context Injection? I cannot think of any but maybe I am missing something?

Charlie S
  • 4,366
  • 6
  • 59
  • 97

2 Answers2

2

On the difference: In addition to that context injection gives you better static type safety. (I have written a post about the decentralized architecture model you can build up with context injection: http://gasparnagy.com/2017/02/specflow-tips-baseclass-or-context-injection/)

Why Scenario Context? First of all, this feature existed before context injection and has been used in many tutorials, etc. So it is somewhat better known.

Also scenario context is somewhat an easier programming concept. You just get and set some global variable. For context injection, you have to understand constructors, instance fields and local variables. I think these are important things to learn anyway, but might be too much at once (without help).

Scenario context might be also useful is when you write generic SpecFlow plugins and you don't want to be dependent on the fine details of the dependency management system of the concrete project, but this is a pretty special case anyway.

Gaspar Nagy
  • 4,422
  • 30
  • 42
  • Agreed, Context Injection is preferrable because it is OO. C# is OO, can't survive in it if you don't know these concepts anyway. – k_rollo Oct 26 '19 at 23:30
0

Scenario context is using strings. Which means you can pass the string as a parameter of your test. You could write a generic test method to store something in a Scenario Context variable. Eg :

public void GenericSaveIntTestMethod(string variableName, int intToSave){

    ScenarioContext.Current[variableName] = intToSave;

}

You could reuse this. Saving different int's with different names. I'm not sure if this is good or bad practice, but I've seen it used in the framework I'm working in. I'm not sure if there is a way to do this with Context Injection.

Megan Styles
  • 631
  • 1
  • 5
  • 10
  • Context Injection uses objects. Might as well create a POCO with those fields. See [here](https://specflow.org/documentation/context-injection/). – k_rollo Oct 26 '19 at 23:28