Sitecore Unit Testing Guide — Part 2 : Using Fixtures

Ehsan
3 min readJun 12, 2022

--

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

In the previous part, we examined mocking Items, Fields and Database and how to write basic unit tests. In this part we will see how to make better tests using the fixtures and reuse the mocking code in our tests

AutoData Attribute

Test fixtures can be used to encapsulate and reuse the code for setting up the objects and data used by tests. We are going to use that for mocking items, templates, databases and other mocked object used in unit tests.

Xunit2.AutoFixture library provides AutoData atrribute which we are going to uses it to simplify our tests. By using this attribute we can automate setup of mock objects that are passed to the tests through the method parameters. To uses this attribute, we will encapsulate our mocking logic into instances of AutoFixture.ICustomization interface. Let’s create three implementations of this interface for Item, Template and Database.

First let’s add an extension method to Database class to add a mock item

Now we will create Customization classes :

Then we will create a custom AutoData attribute and configure it to use our customizations:

So we are ready to use our fixture in our test. Let’s rewrite the tests in the first part using our SitecoreAutoData attribute:

So now to get the mocked Item for personData and child, we just need to specify them as parameters for our test class. Let’s make this even better by adding an extension method for Item class to add a field and remove the AddField method from our test class. We can also add an extension method for adding child items to an item:

So now our test class will look like this:

This test is much more readable and easier to maintain. You can add more extensions to Item and Database classes as needed to shorten your tests.

In next part we will try to add more customizations to our test fixture for mocking other Sitecore services such as LinkManager

--

--

Ehsan

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