Stub Umbraco Dependencies

How to Get Umbraco Dependencies in a Unit Test

Umbraco unit testing TDD Tuesday, May 20, 2014

Before we can test Umbraco, we need to stub some important dependencies like the Umbraco context.

The steps to that are basically:

  1. Go to the Umbraco downloads page
  2. Download the source
  3. Compile and download the Umbraco.Tests dll
  4. Add the dll to a dependencies folder and reference it in your tests project.
  5. Have your tests derive from BaseRoutingTest class
  6. Use the DatabaseTestBehaviour attribute to define if your tests should have a temp database (for integration testing) but in the meantime, let's keep it as no database.
  7. You need to setup a web.config and two umbraco settings files in the setup project. Copy them from the Configurations/UmbracoSettings folder in the Umbraco.Tests project and don’t forget to setup the “Copy to output directory” setting in the Properties to “Copy always” so that the configuration file is available when running the tests (see image below).

    UmbracoSettings copy always to output directory

    In the Umbraco.Tests.dll there’s code that references the umbracoSettings/defaultSettings. If you don’t have it there, it will throw a null reference exception when initializing the UrlProvider inside the GetRoutingContext method.
  8. In your test class setup method (or wherever you want), call GetRoutingContext to get the routing context which also includes the UmbracoContext from which you can get the HTTP context and the Umbraco services.

You'll end up with something like this:

public class HomeDocTypeControllerTests : BaseRoutingTest
    private UmbracoContext umbracoContext;

    public void SetUp()
        this.umbracoContext = this.GetRoutingContext("/").UmbracoContext;

Now we may create unit tests for the classes that depend on Umbraco. Let's start with unit testing an SurfaceController action method.