This is the second part of my unit testing series.  In Unit Testing Part 1 I discussed simple ways that you can organise your project so all the Episerver API dependencies are hidden away in a single file to help improve your sites testability. As of yet we haven't gone into the details of why this helps us so much.

In this article we'll start to write some of the unit tests and, hopefully, it should be clear how using Mocks to swap out all of Episerver's dependencies allows us to create testable code.  Before we start I'll be using three packages available from Nuget:

Injected - Testing A Controller Using Epi Dependencies

If you look in the Alloy site in the controller's folder, you will soon come across the Injected property.  Interfaces wrapped in an Injected are constructed via new the new service locator using the global service locator object.  This is really cool and useful, however, if you try and do the following test you will get an ActivationException

To test dependencies that are injected using Injected<> we use Mock. Mock will create a mock of IEpiDependencies allowing the code within the test to run without it throwing an exception.

If you now create a new Controller, Mock will inject mimic interfaces and classes so our code will load!  This is a big step forward as now you can write unit tests to test the functionality you want.  Below shows a fully working test

Testing Pages and Content Areas

So, now we have covered how to Mockup a controller, the next bit we can move onto is how to Mock a page up.. specifically a page with a Content Area and items within that area.  This one involves a bit more code, I'm still using the [TestFixtureSetUp] method above. In this test, we need to create a content area object, populate it with a content area item object.

We now have a test to ensure that the iContent has been added.  This test in itself is pretty boring but it does give you the framework to start fully testing any part of your page types and content areas you might need. The code for the whole of this series can be found on my github.. here enjoy!