Mocking the UmbracoHelper in Umbraco 9
I’ve always had somewhat of a love-hate relationship with the UmbracoHelper, mostly because until recently it has been a lot of work mocking this little helper.
Part of the reason that I created the base test class in the Official Unit Testing docs for v8 was so that all the logic needed to mock the UmbracoHelper would be gathered in one place, which can be seen here.
UmbracoHelper in v8: A complex little helper!
See the UmbracoHelper is not registered in the IoC container using an interface. There’s no IUmbracoHelper.
And the UmbracoHelper in v8 had a few dependencies (6 to be exact) and one of them was the MembershipHelper, which also did not have use an interface (no IMembershipHelper).
And this MembershipHelper had 10 (!) dependencies including the HttpContext and MembersMembershipProvider (which also had no interface and its own set of required dependencies.). All and all this was a lot to work mock and perform tests on.
God bless you Umbraco v9!
But this is now a thing of the past, since the UmbracoHelper in v9 has been tremendously easier to mock, especially since:
- It only has 3 dependencies.
- and THEY ARE ALL INTERFACES!!!!
So now all you need is to mock the ICultureDictionaryFactory, IUmbracoComponentRenderer and the IPublishedContentQuery and you are good to go!
So instead of needing a big base class with several lines of code, mocking the UmbracoHelper can now be done in just 4 lines of code!
Hands on example
I recently had a good use case for this when I was writing some test for the Umbraco 9 Demo site.
In this example I have a SiteSettings class that I use on various places that takes in the UmbracoHelper to query the content cache and return the SiteName.
So when testing this I mock the returned content from the IPublishedContentQuery.ContentAtXPath (which is the underlying behaviour of the UmbracoHelper.ContentAtXPath) and then make sure that the returned site name is the same as the expected home node name.
Hope it can be useful to someone.
Cheers friends! ❤️