DEV Community

Jeremy Davis
Jeremy Davis

Posted on • Originally published at blog.jermdavis.dev on

3 1

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)
{
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

Simple.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up