My SpecFlow Scenario Context Service

Hackered
Saturday, August 9, 2014
by Sean McAlinden

In order to simplify access to the SpecFlow scenario context I use a simple service class to abstract any checks and simplify key creation.

In the following example usage I am passing the object I want to persist directly into the SaveValue method. Internally the full name of the type will be used as the scenario context key.

Similarly the object can be returned and cleared by just passing the type parameter.

ScenarioContextService.SaveValue(user);
var contextUser = ScenarioContextService.GetValue(); ScenarioContextService.ClearValue(); 

Same as above but inputting the key manually:

ScenarioContextService.SaveValue("MyUser", user);
var contextUser = ScenarioContextService.GetValue("MyUser"); ScenarioContextService.ClearValue("MyUser"); 

And here is my ScenarioContextService class.

 public static class ScenarioContextService
    {
        public static void SaveValue<T>(T value)
        {
            if (value.Equals(default(T)))
            {
                throw new Exception("Value cannot be default value");
            }

            var key = typeof(T).FullName;
            SaveValue(key, value);
        }

        public static void SaveValue<T>(string key, T value)
        {
            if (ScenarioContext.Current.ContainsKey(key))
            {
                ScenarioContext.Current[key] = value;
            }
            else
            {
                ScenarioContext.Current.Add(key, value);
            }
        }

        public static T GetValue<T>()
        {
            var key = typeof(T).FullName;

            return GetValue<T>(key);
        }

        public static T GetValue<T>(string key)
        {
            if (!ScenarioContext.Current.ContainsKey(key))
            {
                throw new ArgumentException("The key does not exist in the scenario context");
            }

            return ScenarioContext.Current.Get<T>(key);
        }
    }