In today's tutorial, you will learn how to unit test service locators and a controller context. When you are aiming for high test coverage in your website, you will inevitably need to test things like service locators, the HTTP context, controllers, base class and a host of other weird and wonderful classes. Sometimes understanding where to start can be a challenge. The aim of this post is to helpfully allow you to get on with these tasks.
How To Test Service Locators
Using service locators within your codebase is considered an anti-pattern, however, in some instances, you simply can't get away from using it. For example, if you build a website with Episerver CMS, you'll likely end up using one in your initialisation modules as you can not use constructor injection. Testing a service locator is actually pretty easy with Moq. When it comes to testing, most things can generally be mocked, sometimes it takes a little persistence to get there though! An example of how to test service location is shown below:
The code's pretty simple. Define a mock IServiceLocator
, use ServiceLocator.SetLocatorProvider
and assign it. After, any time that you add a dependency into your mock service locator, your code will automatically work as expected!
How To Mock Your Controller Context
Often when you are writing unit tests for your controllers, you will need to add some test data into the route data. Setting up the mocking for testing a controller context is more involved, You can do this with this snippet:
Happy Coding 🤘