Unit testing computed fields

Quick one today. I was writing some code for Sitecore Computed Index fields recently, and it took me more Google Effort than I felt it should have to work out how to write unit tests with FakeDB to verify the code worked. If you want to do that without spending a while searching, the answer is pleasingly simple:

When you declare a computed field, the key method you’re implementing looks like this:

public override object ComputeFieldValue(IIndexable indexable)
{
}

But when you implement a test using FakeDb you’re dealing with Item objects:

[TestMethod]
public void ClassUnderTest_Description_OfTheTestCase()
{
    using (var db = ComputedFieldsFakeDb.Create())
    {
        var itm = Sitecore.Context.Database.GetItem("/sitecore/content/TheItemToIndex");
        var sut = new ComputedFieldUnderTest();

        var result = sut.ComputeFieldValue( /* what goes here to do the mapping? */ );

        Assert.AreEqual("somevalue", result);
    }
}

So what do you do to map the Item into an IIndexable?

Well, turns out it’s pretty trivial – There’s a type called SitecoreIndexableItem which wraps an Item to give you an IIndexable:

var result = sut.ComputeFieldValue(new Sitecore.ContentSearch.SitecoreIndexableItem(itm));

Simple.

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 )

Google photo

You are commenting using your Google 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

This site uses Akismet to reduce spam. Learn how your comment data is processed.