Sharing Data Between SpecFlow Steps

SpecFlow is the open source port of Cucumber for .NET environment. You can define automatic tests in Gherkin and execute them using MSTest, NUnit and many other unit testing frameworks.

In this article, I’ll tell you how to share data between SpecFlow steps.

If you are already familiar, BDD approach let you define test steps for every user action. Here’s an example:

Given the customer has logged into their current account
And the balance is shown to be 100 euros
When the customer transfers 75 euros to their savings account
Then the new current account balance should be 25 euros

Every step is executing a different C# code. As you can see most of the test data is hardcoded. Mostly we have dynamic data in our tests that are used in more than one step.

So, how do we share that data across steps?

Let’s see…

Solution 1: Quick and Dirty Solution – Create Private Variables

You can create private variables to store dynamic values. Even though it’s a working solution, for every dynamic data you need to create a new variable. So we don’t get to keep as we’ll propose a better solution.

Solution 2:  SpecFlow ScenarioContext

ScenarioContext is a static object coming with SpecFlow library. This object is always on your service to keep any kind of variable in the memory during test execution. You can use ScenarioContext in any binding classes.

How to Use?

There’re two main methods of ScenarioContext. One sets the data with a key and other one gets the data by the key.

ScenarioContext.Current[“key“] = value;

var value = ScenarioContext.Current[“key“]

By using the above set convention, you can set a value into ScenarioContext and retrieve it. The only thing that’s important is to cast the retrieved value into proper type.

Some Conversion Examples

You’ll find 3 different examples of casting. 

var value = (int)ScenarioContext.Current[“key“]
var value = (string)ScenarioContext.Current[“key“]
var value = (ObjectName)ScenarioContext.Current[“key“]

Solution: ScenarioContext.Current

There’s another version of ScenarioContext. Here’s an example of how to use it.

ScenarioContext.Current.Add(string key, object value);
var value = ScenarioContext.Current.Get<Type>(string Key);

Hope this tutorial helps your SpecFlow projects.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.