0

I am using NEST framework to do elastic search query in c#.

I am writing a simple unit test with Moq.

mockElasticClient.Setup(ec => ec.SearchAsync(
                                    It.IsAny<Func<SearchDescriptor<Relativity>,
                                            SearchDescriptor<Relativity>>>()))
                                    .ReturnsAsync(mockSearchResponse.Object);

THe above code throws 'An expression tree may not contain a call or invocation that uses optional arguments'

the above code is working if i use Search instead of SearchAsync.

What am i doing wrong here?

spottedmahn
  • 14,823
  • 13
  • 108
  • 178
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156
  • https://stackoverflow.com/questions/12413583/an-expression-tree-may-not-contain-a-call-or-invocation-that-uses-optional-argum you have to pass the argment with default value manually. – LeBigCat Nov 29 '18 at 16:42
  • Thank you. it really helped me. – Mukil Deepthi Nov 29 '18 at 17:00
  • In this below case how to do the mocking, could some one please help me over here, i am also facing same issue. ISearchResponse response = await _elasticClient.SearchAsync(s => s.Query(qry => qry.Raw(query))).ConfigureAwait(false); – AnilkumarReddy Sep 14 '21 at 17:25

1 Answers1

0

All the parameters in a mocked function should be accounted for. In this case as from the function definition

    //
    // Parameters:
    //   selector:
    //     A descriptor that describes the parameters for the search operation
    //
    // Type parameters:
    //   T:
    //     The type used to infer the index and typename as well describe the query strongly
    //     typed
    Task<ISearchResponse<T>> SearchAsync<T>(Func<SearchDescriptor<T>, ISearchRequest> selector = null, CancellationToken cancellationToken = default) where T : class;

there are two parameters Func<SearchDescriptor, ISearchRequest>selector, and CancellationToken.

Mocking required that the CancellationToken Mocked as here below

mockElasticClient.Setup(x => x
            .SearchAsync(It.IsAny<Func<SearchDescriptor<Relativity>, ISearchRequest>>(),It.IsAny<CancellationToken>()))
            .ReturnsAsync(mockSearchResponse.Object);
Daniel Kiptoon
  • 314
  • 1
  • 7