0

I have the following code that returns Items:

public static IList<Item> GetAll(Language language)
{
    var index = $"my_index_{Context.Database.Name.ToLowerInvariant()}";
    using (var context = ContentSearchManager.GetIndex(index).CreateSearchContext())
    {
        var results = context.GetQueryable<SearchResultItem>().InLanguage(language);
        return results.ToList();
    }
}

I want to unit test some code that uses this function. I have set up FakeDb to use in the test as below:

using (var db = new Db
{
    new DbItem("Home") {{"Title", "Welcome!"}}
})
{
    sitecoreReader.GetAllThings(); //this in turn calls GetAll(Language language)
}

Now when the code hits the line using (var context = ContentSearchManager.GetIndex(index).CreateSearchContext()) it throws this error:

Sitecore.ContentSearch.Exceptions.IndexNotFoundException

Google is not helping me on this one...

Update: using the answer below and the FakeDb documentation I was nearly able to unit test my code. I hit a wall with it when I realised my query uses extension methods that cannot be Moq'd!

The code needs some serious refactoring to be able to test!

1 Answer 1

1

As it is hard to write your unit tests in an answer here, I'll try to give you some overal guidance..

For unit testing code that uses index queries I usually start with a custom Queryable stub as you can find here: https://gist.github.com/vivianroberts/1a632d8bfb8fa62e23c4679b086728ce

What I like about that approach is that it is very easy to setup test data on a single spot and use that data to extensively test your query code with all kind of predicates without having to extend this base code.

I did bump into issues with this code when using facets though (as seen on Unit testing contentsearch with facets).

What this approach actually does is creating your own ISearchContextBuilder and injecting that in your tests (instead of the default one). Each search builder can be used to do all sorts of test on the same data set. If you need to test other data sets, you create another builder but you can re-use the stub from the gisthub.

2
  • Great thanks, I have an error on line 60 - SearchResults and SearchHit are not recognised. Where do these come from?
    – Percy
    Commented Nov 28, 2018 at 8:32
  • Ah I need a nuget package Sitecore.ContentSearch.Linq
    – Percy
    Commented Nov 28, 2018 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.