Search code examples
c#testingnestfakeiteasy

Can't get right parameters right in my A.CallTo FakeItEasy method


I'm trying to create a simple test to check if the search method to the elasticsearch client has been called.

public async Task<IReadOnlyCollection<MyClass>> MySearch(string term)
    {
        var searchResponse = _elasticClient.Search<MyClass>(s => s
            .AllIndices()
            .Query(body => body
                .MultiMatch(m => m
                    .Query(term))));

        return searchResponse.Documents;
    }

This is the test:

[Fact]                                                                                           
public async Task MyTest()          
{                                                                                                
    await _searchAgent.MySearch(_term);                                            

    A.CallTo(() => _elasticClient.Search<MyClass(A<ISearchRequest>._))
            .MustHaveHappened();                                                                     
 }                                                                                            

I don't quite understand the error message here. It looks like something is wrong with the parameters in the A.CallTo method, but I thought I ignore the input with A<ISearchRequest>._ ?

FakeItEasy.ExpectationException : 

Assertion failed for the following call:

Nest.IElasticClient.Search`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle](request: <Ignored>)
Expected to find it once or more but didn't find it among the calls:
1: Nest.IElasticClient.Search`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle](selector: System.Func`2[Nest.SearchDescriptor`1[RiksTV.Api.ContentSearch.Model.ContentSearchTitle],Nest.ISearchRequest])

Solution

  • You are actually using this method on ElasticClient

    ISearchResponse<TDocument> Search<TDocument>(
          Func<SearchDescriptor<TDocument>, ISearchRequest> selector = null)
          where TDocument : class
    

    not

    ISearchResponse<TDocument> Search<TDocument>(ISearchRequest request) where TDocument : class;
    

    so you need to change your A.CallTo(..) a little bit to

    A.CallTo(() => elasticClient.Search(A<Func<SearchDescriptor<MyClass>, ISearchRequest>>._))
        .MustHaveHappened();
    

    Hope that helps.