Skip to content

Instantly share code, notes, and snippets.

@kevinbrechbuehl
Created July 22, 2015 11:23
Show Gist options
  • Save kevinbrechbuehl/ac99844e1771ab3cce80 to your computer and use it in GitHub Desktop.
Save kevinbrechbuehl/ac99844e1771ab3cce80 to your computer and use it in GitHub Desktop.
Sitecore Content Search Unit Test
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Moq;
using NUnit.Framework;
using Sitecore.ContentSearch;
using Sitecore.ContentSearch.Linq;
using Sitecore.ContentSearch.SearchTypes;
namespace Website
{
[TestFixture]
public class ContentSearchTest
{
[Test]
public void GetProductsTest()
{
// arrange
var repository = new TestableSearchRepository();
// act
var products = repository.GetProducts(null);
// assert
Assert.AreEqual(2, products.Count());
}
}
public class ProductSearchResultItem : SearchResultItem
{
[IndexField("free")]
public virtual bool Free { get; set; }
}
public class SearchRepository
{
public virtual IEnumerable<ProductSearchResultItem> GetProducts(SitecoreIndexableItem item)
{
using (var context = this.GetSearchContext(item))
{
var query = context.GetQueryable<ProductSearchResultItem>();
var allProducts = query.GetResults();
var products = query.Filter(searchResultItem => searchResultItem.Free);
return products.ToList();
}
}
protected virtual IProviderSearchContext GetSearchContext(SitecoreIndexableItem item)
{
return ContentSearchManager.CreateSearchContext(item);
}
}
public class TestableSearchRepository : SearchRepository
{
protected override IProviderSearchContext GetSearchContext(SitecoreIndexableItem item)
{
// create the magic product index
var index = new List<ProductSearchResultItem>();
index.Add(new ProductSearchResultItem { Free = true });
index.Add(new ProductSearchResultItem { Free = false });
index.Add(new ProductSearchResultItem { Free = true });
// create the mock context
var context = new Mock<IProviderSearchContext>();
context.Setup(c => c.GetQueryable<ProductSearchResultItem>()).Returns(index.AsQueryable());
return context.Object;
}
}
public static class ExtensionMocks
{
public static SearchResults<TSource> GetResults<TSource>(this IQueryable<TSource> source)
{
return new SearchResults<TSource>(source.Select(s => new SearchHit<TSource>(0, s)), 0);
}
public static IQueryable<TSource> Filter<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)
{
return source.Where(predicate);
}
}
}
@jordanrobinson
Copy link

This is really useful, but in case anyone ends up in the same situation as me, this doesn't work for queries involving facets.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment