ScenarioContext in Specflow

How to pass values between step definitions in Specflow or Can we use the data of a step definition in the next steps or multiple steps.

ScenarioContext in Specflow is the solution to this problem. ScenarioContext is a class in Specflow that help to pass data between the test steps.

ScenarioContext shares the data between step only not in the scenario or Testcase.

How to pass values between step definitions in Specflow

We can set the current state of ScenarioContext as a value and get the same value in the next step or at the required step but only in the same Testcase.

Set the data in ScenarioContext

ScenarioContext.Current.Add("PageTitle", “Scenario Context in Specflow”);

In the above code Add(“Key”, “Value”) will take two-parameters Key and value. Where the key is unique name that will use to get the value in the next step.

Get the data in ScenarioContext

string PageTitle= ScenarioContext.Current["PageTitle"].ToString();

Example to share the data between steps in Specflow

In this example, We will write a BDD automation Testcase to login to the application using. And share the “UserName” in the next step to verify the user after login.

Test Scenario:

Scenario: Login
Given User is navigated to login page
When User enters username and password
Then User is able to login in the application

Step Definition:

[Given(@"User is navigate to login page")]
public void GivenUserIsNavigateToLoginPage()
Driver.Navigate().GoToUrl(BaseURL + "/login.aspx");

[When(@"User enter username and password")]
void WhenUserEnterUsernameAndPassword()
//Set UserName as the current state of ScnearioContext
ScenarioContext.Current.Add("UserName", "User123");
Page.LoginPage.Login("UserName", "Password");


[Then(@"User is able to login in the application")]
public void ThenUserIsAbleToLoginInTheApplication()
//Get UserName as the current state of ScnearioContext
string UserName = ScenarioContext.Current["UserName"].ToString();
//Print the username get from the current state of Snceario context
Console.WriteLine("Loged in User is: "+ UserName);