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
1 |
IGetUmbracoService |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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); } } |