Mocking calls to ApplicationContext.Current.Services

My current contract involves working on a project based on Umbraco.

Unit testing Umbraco, can be a bit tricky, especially given the existence of the static ApplicationContext.Current.Services class, which contains handy references to the Umbraco services – provided by a static type! We can’t mock this.

So, I created a little wrapper around this that would allow us to mock the returned service, via an interface

IGetUmbracoService

In the implementation, I use reflection to return the underlying service from ApplicationContext.Current:

    public class GetUmbracoService : IGetUmbracoService
    {
        public T GetService()
            where T : IService
        {
            var serviceTypeProperty = ApplicationContext.Current.Services
                .GetType()
                .GetProperties()
                .SingleOrDefault(x => x.PropertyType == typeof(T));

            if (serviceTypeProperty == null)
            {
                return default(T);
            }

            return (T)serviceTypeProperty
                .GetValue(ApplicationContext.Current.Services);
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *