Quick creation of a Sitecore Item to pass in unit tests

This is a super quick post.

In quite a number of test scenarios I would choose to abstract the ‘doing’ something with a Sitecore item to a repository class that could only be integration tested. This would mean that for that test scenario, generally the only necessity is to ensure that the item is not null, then rely on the repository to do the real work for me.

I recently came up with this method of creating a dummy item to enable unit testing of a method that takes an item as a parameter. Note – this is no substitute for FakeDb – but in the majority of scenarios – for real unit testing, I would be using Glass Mapper anyway.

Here is a simple method to create a test item without any app.config or anything.

        private Item GetTestItem(Guid itemId, Guid templateId, Guid branchId, string itemName)
            ID actualItemId = new ID(itemId);
            Database database = FormatterServices.GetUninitializedObject(typeof (Database)) as Database;
            ItemDefinition itemDefinition = new ItemDefinition(actualItemId, itemName, new ID(templateId), new ID(branchId));
            ItemData itemData = new ItemData(itemDefinition, Language.Parse("en"), new Version(1), new FieldList());
            Item item = new Item(actualItemId, itemData, database);
            return item;

So an example test call for my code would look like the following (using my toolset choice of Nunit, NSubstitute & Fluent Assertions)

        public void EvaluateRulesFromField_for_correct_data_returns_true()
            // Arrange
            RulesManagerTestHarness testHarness = new RulesManagerTestHarness();

            Guid itemId = Guid.NewGuid();
            Guid templateId = Guid.NewGuid();
            Guid branchId = Guid.Empty;
            string itemName = "fred";

            Item item = GetTestItem(itemId, templateId, branchId, itemName);

            // Act
            bool result = testHarness.RulesManager.EvaluateRulesFromField("fieldName", item);

            // Assert

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s