Search code examples
c#.netmoqdotcover

Mock extension methods IElasticClient


Is there a way to mock the following

        var result = await Client.SearchAsync<IndexedSite>(d => d
            .Index(SiteIndexName)
            .Query(q => q.MatchAll())
            .Sort(sd => sd.Field(s => s.Name, SortOrder.Ascending))
            .Take(c_maxSiteListSize));

Would one use .Callbacks in this situation?

My current setup:

    private Mock<IElasticClient> _client = new Mock<IElasticClient>();
    private Mock<ISearchResponse<IndexedSite>> indexedSite = new Mock<ISearchResponse<IndexedSite>>();

    _client.Setup(x =>
        x.SearchAsync<IndexedSite>(It.IsAny<Func<SearchDescriptor<IndexedSite>, ISearchRequest>>(),
            default(CancellationToken))).Returns(Task.FromResult(indexedSite.Object));

This works, and it does return indexedSite, however it does not 'Cover' .Index/.Query/.Sort/.Take extension methods, which is what I want.


Solution

  • Per @Olegl answer. It is not possible to Mock extension methods. You need to refactor and get rid of extension methods in order to make it testable

    More info here