Unit Testing
A guide to getting started with unit testing in Umbraco
These examples inspire unit testing in Umbraco with Umbraco 9.x, 10.x, 11.x and 12.x, using NUnit, Moq, and AutoFixture. There are many ways of testing Umbraco and there’s no right or wrong way.
When testing components in Umbraco, such as controllers, helpers, services etc. these components often require that you provide a couple of dependencies in your classes using dependency injection. This is because a lot of magic happens “under the hood” of Umbraco and these dependencies are needed for that magic to happen.
Mocking
These tests follows an approach thats based on isolating your tests from Umbraco and mock as much of Umbraco’s dependencies as possible. Think of it like you’re not testing Umbraco, you’re testing how your implementation code interacts with Umbraco’s behavior.
Once you get familiar with these underlying dependencies you might want to start looking into replacing them with actual implementations. This leans more towards integration or E2E testing. Again these examples should be a source of inspiration and the quickest way to get started with Unit Testing.
Testing a ContentModel
See Reference documentation on Executing an Umbraco request.
public class PageViewModel : ContentModel
{
public PageViewModel(IPublishedContent content) : base(content) { }
public string Heading => (string)this.Content.GetProperty(nameof(Heading)).GetValue();
}
public class PageViewModelTests
{
[Test, AutoData]
public void Given_PublishedContent_When_GetHeading_Then_ReturnPageViewModelWithHeading(string value, Mock<IPublishedContent> content)
{
SetupPropertyValue(content, nameof(PageViewModel.Heading), value);
var viewModel = new PageViewModel(content.Object);
Assert.AreEqual(value, viewModel.Heading);
}
public void SetupPropertyValue(Mock<IPublishedContent> content, string propertyAlias, string propertyValue, string culture = null)
{
var property = new Mock<IPublishedProperty>();
property.Setup(x => x.Alias).Returns(nameof(PageViewModel.Heading));
property.Setup(x => x.GetValue(culture, null)).Returns(propertyValue);
content.Setup(x => x.GetProperty(propertyAlias)).Returns(property.Object);
}
}Testing a RenderController
See Reference documentation for Custom controllers (Hijacking Umbraco Routes).
Testing a SurfaceController
See Reference documentation on SurfaceControllers.
Testing a Controller
Testing ICultureDictionary using the UmbracoHelper
Last updated
Was this helpful?