EPiServer: Dependencies in Episerver Explained – Unit Testing Part 1

Trying to get 100% test coverage in your project is a noble goal.  With Episerver 7 onwards, unit testing is a lot more achievable.  In olden times, you may have a class that called the DataFactory to get some information from Episerver.  Doing this created a dependency to Episerver in your code.  When you came to writing a unit test you would try to run it and you would get something like a NullReference error or some other annoyance.

The key to creating testable code is to remove all dependencies in your  code.  In other words you cannot use new Object anywhere in your business layer.  Instead, you will need to inject all your dependencies through your classes constructor.  When you look at the CMS commerce you’ll find you have a lot of dependencies but in this article I’m going to assume you only care about the CMS parts.

In Episerver 7 IContentRepository and ILinkResolver.  You can use something like this

var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance();
var pageReference= pageRouteHelper.PageLink;

However, you cannot test this code easily, as when you run your unit test it will throw an unwanted exception.  What I suggest you do to get around this problem is to create a single class that handles all of these Episerver dependencies.  In today’s post I will call this EpiserverDependencies and my class will look like this:

using EPiServer.Core;
namespace EpiserverDependencies
{
/// <summary>
/// The Pages' and blocks' dependencies
/// </summary>
public class EpiserverDependencies : IEpiserverDependencies
{
private  readonly Lazy<IContentRepository> _contentRepository;
private  readonly Lazy<ILinkResolver> _linkResolver;
public BaseDependencies(
IContentRepositoryFactory contentRepositoryFactory,
ILinkResolverFactory linkResolverFactory)
{
_contentRepositoryFactory = new Lazy(contentRepositoryFactory.GetContentRepository());
_linkResolverFactory = new Lazy(linkResolverFactory.GetLinkResolver());
}
public ILinkResolver LinkResolver
{
get
{
return _linkResolverFactory;
}
}
public IContentRepository ContentRepository
{
get
{
return _contentRepositoryFactory;
}
}
}
}

What this code is doing is passing in a IContentRepositoryFactory and ILinkResolverFactory.  These are two custom factories that I have created that will create the Episerver dependancies.  I also use the Lazy to store the IContentRepository and ILinkResolver.  If you have never come across Lazy it allows you to only instantiate something the first time its actually used.  As this class will be passed into every base controller (read on for explanation) but the dependencies might not be used on each page request so delaying the creating until/when it’s needed saves processing time.  If you look at the bottom of this article full source code is included 🙂

So now we have a class that will make our lives unit testing much easier..  how do we actually use it in a website?

The first thing you need to do is inject your dependencies into your website, via in this case, Structure Map (as it comes out the box with Episerver).  The following code shows how you would do this:

 

Now we have a set-up structure map to inject our base dependencies whenever a call to IEpiserverDependencies is made.   Our next step is to actually start injecting our dependencies so we can use them.  The starting point for all of your pages and blocks will be a controller.  In Episerver it is highly recommended that in your project you use a base controller.  This allows you to add some common features like your base dependencies and SSL for example to every page in your site very easily.  Below shows you an example of my base controller

namespace BasePageController
{
public class BasePageController<T> : PageController<T>, IEpiserverDependenciesResolver
where T : GlobalBasePage
{
private Injected<EpiserverDependencies> epiServerDependencies Service;
protected EpiserverDependencies EpiserverDependencies
{
get { return baseDependenciesService.Service; }
}
IEpiserverDependencies IEpiserverDependenciesResolver.EpiserverDependencies
{
get { return EpiserverDependencies; }
}
}
}

The next step in this process is to create an actual controller for a page type that we have already created.  In this example I am going to use an example page called Content.

public class ContentPageController : BasePageController<ContentPage>
{
public ActionResult Index(ContentPage currentPage)
{
return View("Index", new ContentPageViewModel(currentPage, EpiserverDependencies));
}
}

In our controller we pass a Content Page View Model to a view.  Some people get confused what the point of a View Model is compared to just writing code within a controller.  For me, a controller is the place that the routing engine looks for when it’s trying to resolve a URL.  The controller is responsible for managing that view, adding caching, authorization, handling query string.  A controller is not the place to put your logic for your page type, that should be done in a view model.

Now we have that cleared up, lets see what the Content Page View Model looks like:

 

namespace Example
{
public class ContentPagePageViewModel : GlobalViewModel<ContentPage>
{
private readonly IEpiserverDependencies _epiServerDependencies;
public BlogHomePageViewModel(ContentPage currentPage, IEpiserverDependencies epiServerDependencies)
: base(currentPage)
{
_epiServerDependencies = epiServerDependencies;
}
}
}

In our view model we have passed in an instance of the current page and our epiServerDependencies.  The View Model inherit from GlobalViewModel, code below for reference but there is nothing special about it:

 

public class GlobalViewModel<T> : IPageViewModel<T> where T : GlobalBasePage
{
public GlobalViewModel(T currentPage)
{
CurrentPage = currentPage;
}
public T CurrentPage { get; private set; }
public LayoutViewModel Layout { get; set; }
public IContent Section { get; set; }
}

Wow.. that was a lot of code.  Lets re-cap, we have created a global class that will be passed around the whole of your web project removing any Episerver dependencies from your code base.  Any place you need to use the Episerver API you do it through this class.  This is the most important part if you want your code to be testable.  Any class that needs to use these dependencies you will need to pass a IEpiserverDependencies in via a constructor.

To get IEpiserverDependencies to use the right dependencies when we start our website via a browser and IIS, we need to configure a dependency injection service.  In Episerver this has been achieved by configuring a structure map (comes with the project) to pass in EpiserverDependencies whenever a base controller is called via the routing engine, e.g. a page request has been made.

All the controllers in our project will inherit from our Base Controllers class.  This class gives access to all the pages in our website using EpiserverDependencies.  in each page controller we return a View Model back to the view.  This view model will contain business logic relevant to the current page request.

In these View Models we will have business logic that we will want to unit test so we don’t want to have any hard coded Episerver dependencies written in here so we inject them into out View Model via our controller.

So now we have our dependencies injected into our View Model lets use them!  So In our code we can now do something like this:

GetContentPageCount(_epiServerDependencies.ContentRepository)
public static int GetContentPageCount(IContentRepository _repository)
{
return _repository.GetChildren<ContentPage>(currentPage).Count();
}

 

This is a very small example but you have now removed the dependancy from Episerver.  If you wanted to unit test this simple method you could either create a fake Content Repository and pass it in, or use something like MOQ to MOQ the dependency in your SetUp method in your unit test case.

That wraps up the first in this series of how to unit test in Episerver and as of yet we have yet to write a single test!  What we have achieved is a written framework that will allow us to unit test anything in our code that uses the Episerver API which is a huge step forward.  In the next chapter of this Epi saga I will show you how you can write tests using fakes or the more popular mocks.

The code for the whole of this series can be found on my github.. here enjoy 🙂

 

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

6 replies

Trackbacks & Pingbacks

  1. […] To learn a bit more about good practice patterns to be used within EpiServer I would recommend reading EPiServer: Dependencies in EpiServer Explained – Unit Testing Part 1 […]

  2. […] To learn a bit more about good practice patterns to be used within EpiSErver I would recommend reading EPiServer: Dependencies in EpiServer Explained – Unit Testing Part 1 […]

  3. […] I’m also exposing a ContentReference to the current page for the redirect part in the form. In this example you might be wondering what _epiServerDependencies is? I suggest you download the code project at the bottom or read by article EPiServer: Dependencies in EpiServer Explained – Unit Testing Part 1 […]

  4. […] I’m going to assume you have a base block controller. If you have no idea what I’m talking about then download my free epi project with epi server dependencies and look in the controllers folder from this page EPiServer: Dependencies in EpiServer Explained . […]

  5. […] code for the link resolver in this article but if you want to get yourself a copy have a look at my Dependencies […]

  6. […] EPiServer: Dependencies in EpiServer Explained – Unit Testing Part 1 […]

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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