DEV Community

Jeremy Davis
Jeremy Davis

Posted on • Originally published at on

Unit testing Sitecore 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:

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));


Discussion (0)