In Specflow, Step definitions are global. So a scenario can have multiple step definitions which can be present in different classes. Sometimes, there arise a need to share the data between steps residing in different classes. How do we do it??
There are multiple ways to do it
Context Injection
Feature Context
Scenario Context
Let us look into more details about how to store and retrieve data using Scenario Context .
ScenarioContext.Current
How do we add a key value pair to Scenario Context ? It is as simple as below
[Given(@"I have entered (.*) and (.*) into the Login Page")]
public void GivenIHaveEnteredAndIntoTheLoginPage(string p0, string p1)
{
ScenarioContext.Current.Add("username", p0);
ScenarioContext.Current.Add("password", p1);
}
How do we retrieve the value from ScenarioContext ?
When(@"I press retrieve data")]
public void WhenIRetrieveData()
{
string username = (string)ScenarioContext.Current["username"];
string password = (string)ScenarioContext.Current["password"];
}
Note: While retrieving , scenarioContext.Current always return an object . Hence we need use explicit casting while retrieving data from scenario context.
In Nut Shell,
**Get a value of the key ( Retrieve data) ** var value =(Type) ScenarioContext.Current.[string Key];
var value = ScenarioContext.Current.Get(string Key);
We can use this for storing and passing objects as well
ScenarioContext.Current.Add(“driver1”, browser);
IWebDriver driver2 = (IWebDriver)ScenarioContext.Current[“driver1”];