My SpecFlow Global Test Context Service

Hackered
Saturday, August 9, 2014
by Sean McAlinden

I often have variables and objects that remain constant throughout the test run.

I have recently been using a global test context service in order to follow the same pattern as my scenario context service and feature context service.

 

The following is an example usage using the types full name as the context key:

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

The following is an example usage where I explicitly set the context key.

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

Here is my GlobalContextService class:

public class GlobalContextService
    {
        private static readonly Dictionary<string, object> GlobalContextItems = new Dictionary<string, object>();

        private static readonly Guid TestRunIdentifier;

        static GlobalContextService()
        {
            TestRunIdentifier = Guid.NewGuid();
        }

        public static Guid TestRunId
        {
            get
            {
                return TestRunIdentifier;
            }
        }

        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 (GlobalContextItems.ContainsKey(key))
            {
                GlobalContextItems[key] = value;
            }
            else
            {
                GlobalContextItems.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 (!GlobalContextItems.ContainsKey(key))
            {
                return default(T);
            }

            return (T)GlobalContextItems[key];
        }
    }