My SpecFlow Feature Context Service

Hackered
Saturday, August 9, 2014
by Sean McAlinden

In order to simplify access to the SpecFlow feature 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 feature context key.

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

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

Same as above but inputting the key manually:

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

And here is my FeatureContextService class.

 public static class FeatureContextService
    {
        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 (FeatureContext.Current.ContainsKey(key))
            {
                FeatureContext.Current[key] = value;
            }
            else
            {
                FeatureContext.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 (!FeatureContext.Current.ContainsKey(key))
            {
                return default(T);
            }

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

        public static void ClearValue<T>()
        {
            var key = typeof(T).FullName;
            ClearValue(key);
        }

        public static void ClearValue(string key)
        {
            if (FeatureContext.Current.ContainsKey(key))
            {
                FeatureContext.Current.Remove(key);
            }
        }
    }