Posted on • Originally published atblog.jermdavis.dev 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:
publicoverrideobjectComputeFieldValue(IIndexableindexable){}
But when you implement a test using FakeDb you’re dealing withItem
objects:
[TestMethod]publicvoidClassUnderTest_Description_OfTheTestCase(){using(vardb=ComputedFieldsFakeDb.Create()){varitm=Sitecore.Context.Database.GetItem("/sitecore/content/TheItemToIndex");varsut=newComputedFieldUnderTest();varresult=sut.ComputeFieldValue(/* what goes here to do the mapping? */);Assert.AreEqual("somevalue",result);}}
So what do you do to map theItem
into anIIndexable
?
Well, turns out it’s pretty trivial – There’s a type calledSitecoreIndexableItem
which wraps anItem
to give you anIIndexable
:
varresult=sut.ComputeFieldValue(newSitecore.ContentSearch.SitecoreIndexableItem(itm));
Simple.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse