Sitecore Unit Testing Guide — Part 3 : Mocking Sitecore Services

Ehsan
3 min readJun 12, 2022

--

Find the source code here : https://github.com/ehsanaslani/SitecoreUnitTesting

In the previous parts we looked at mocking sitecore Items and Databases and writing more readable tests using Fixtures. In this part we will review unit testing other Sitecore services such as LinkManager and ItemManager.

Most of the Sitecore services are derived from abstract classes that can be utilized for mocking these services in our unit tests. For example LinkManager is derived from BaseLinkManager and ItemManager from BaseItemManager.

Before everything, we need to make sure that our code is testable. The dependencies such as LinkManager should be injected through the constructor to make our classes testable. So instead of this:

We should write our class in this way so we can inject our mocked LinkManager to our class and unit test it:

However, you can still unit test the code written in the first sample which directly uses the static Sitecore.Links.LinkManager. We will look into that in the next part.

so let’s write a unit test for our method. First let’s add the BaseLinkManager to the fixture we created in the previous part:

So our test will look like this:

Now let’s look at another example. In this example our code is trying to read the settings in configuration to verify whether Foo setting is enabled:

First, as we did in the previous example, let’s make our code testable by using the BaseSettings class and injecting it through constructor:

Next we can add it to our fixture:

And then we can write our unit test:

You can do the same for any other Sitecore service that you use in your code such as MediaManager, CorePipelineManager, AuthenticationManager, IndexResolver and etc. All you need to do is to find the base abstract class that this services are derived from or the interface that they implement and then you can mock them and add them to your fixture so you can use it in all your tests.

In next part, we will look at mocking the ServiceLocator which can be useful when you are dealing with static classes or when you don’t want to inject the dependencies through constructor for any reason.

--

--

Ehsan

I’m a software architect specialized in Sitecore content management solutions