November Happy Hour will be moved to Thursday December 5th.

Unit Testing For Search.

Vote:
 

This is my search service class

public class SearchService : ISearchService
    {
        #region Private Members

        /// <summary>
        /// The client.
        /// </summary>
        private readonly IClient client;

        /// <summary>
        /// Content locator
        /// </summary>
        private readonly ContentLocator contentLocator;

        #endregion

        #region Constructor

        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="contentLocator"></param>
        public SearchService()
        {
            this.client = SearchClient.Instance;
            this.contentLocator = ServiceLocator.Current.GetInstance<ContentLocator>();
        }

        /// <summary>
        /// initialize service
        /// </summary>
        public SearchService(IClient client, ContentLocator contentLocator)
        {
            this.client = client ?? SearchClient.Instance;
            this.contentLocator = contentLocator ?? ServiceLocator.Current.GetInstance<ContentLocator>();
        }

        #endregion

        #region Public Method

        /// <summary>
        /// Search results
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <param name="page"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public UnifiedSearchResults Search(string searchQuery, string tag, int page, int pageSize)
        {
            var startPage = contentLocator.StartPage;
            ITypeSearch<ISearchContent> query = client.UnifiedSearchFor(searchQuery, Language.English)
              .UsingSynonyms()
              .UsingAutoBoost()
              .ApplyBestBets(true)
              .Track();

            //exclude interal content if user not logged in
            if (!HttpContext.Current.User.Identity.IsAuthenticated
                && !ContentReference.IsNullOrEmpty(startPage.GlobalData.InternalRootPage)
                && !ContentReference.IsNullOrEmpty(startPage.GlobalData.InternalMediaRootPage))
            {
                query = query.Filter(x => !((IContent)x).Ancestors().Match(startPage.GlobalData.InternalRootPage.ID.ToString()));
                query = query.Filter(x => !((IContent)x).Ancestors().Match(startPage.GlobalData.InternalMediaRootPage.ID.ToString()));
            }

            //exclude images 
            query = query.Filter(x => !x.MatchTypeHierarchy(typeof(ImageData)));

            //exclude waypoint publication page, as view not defined for that
            query = query.Filter(x => !x.MatchType(typeof(WaypointPublicationPage)));

            //exclude json file
            query = query.Filter(x => !x.SearchFileExtension.Match("json"));

            //exclude container pages

            //filter by tag
            if (!string.IsNullOrWhiteSpace(tag))
            {
                query = query.Filter(x => x.SearchCategories.Match(tag));
            }

            // TODO facets
            /*
            query = query.TermsFacetFor(x => x.SearchCategories);

            var dateRanges = this.DateRangeFacets.Values.ToList();
            query = query.RangeFacetFor(x => x.SearchPublishDate, dateRanges.ToArray());

            if (FromDate != DateTime.MinValue)
            {
                query = query.FilterHits(x => x.SearchPublishDate.BeforeNow(FromDate, true, true));
            }
            */

            //pagination
            query = query
                .Skip((page - 1) * pageSize)
                .Take(pageSize);

            var hitSpec = new HitSpecification
            {
                HighlightExcerpt = true,
                EncodeTitle = false,
                EncodeExcerpt = false,
                HighlightTitle = true,
                PreTagForAllHighlights = "<em><strong>",
                PostTagForAllHighlights = "</strong></em>",
                ExcerptLength = 500
            };

            return query
                .GetResult(hitSpec);
        }
        ---
        
I am using FakeItEasy to write down unit testing and to create a mock objects.

searchService = A.Fake<ISearchService>();
A.CallTo(() => searchService.Search(query, string.Empty, 1, 10)).Returns(GetSearchResults(query, string.Empty, 1, 10));
        
    
Below is fake method to get results

 private UnifiedSearchResults GetSearchResults(string searchQuery, string tag, int page, int pageSize)
{
    var searchResult = new SearchResult<UnifiedSearchHit>()
    {
        Hits = new HitCollection<UnifiedSearchHit>()
        {
            Total = 2
        }
    };

    searchResult.Hits.Hits = new List<SearchHit<UnifiedSearchHit>>() {
        new SearchHit<UnifiedSearchHit>()
        {
            Id = "Id_1",
            Index = "Index",
            Document = new UnifiedSearchHit<Models.Pages.StartPage>()
            {
                Excerpt = "Excerpt",
                Title = "Title",
                Url = "/",
            }
        },
        new SearchHit<UnifiedSearchHit>()
        {
            Id = "Id_2",
            Index = "Index",
            Document = new UnifiedSearchHit<StandardPage>()
            {
                Excerpt = "Excerpt",
                Title = "About Us",
                Url = "About-us",
            }
        }};

    UnifiedSearchResults results = new UnifiedSearchResults(searchResult);
    return results;
}


Expectation was searchService.Search will return result for Hits.
But it's not returing any Hits. 
Did I miss something.

        

#249957
Edited, Mar 12, 2021 7:40
Vote:
 

Hi Dipak,

You can refer Henrik's blog https://world.episerver.com/blogs/Henrik-Fransas/Dates/2015/1/how-to-do-unit-testing-on-episerver-find/ for the unit testing of find.

#249958
Mar 12, 2021 8:06
Vote:
 

Hello Sanjay,

I have been started my unit testing for search by taking this reference only.

Dipak 

#249960
Mar 12, 2021 9:55
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.