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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay