0

I have a method that inserts documents into Azure cognitive search but I am struggling to unit-test the method. My method looks like below:

public async Task AddDocumentIntoIndexAsync(Document[] Documents, string IndexName)
        {
                IndexDocumentsBatch<CreClaim> batch = IndexDocumentsBatch.MergeOrUpload(Documents);
                try
                {
                    IndexDocumentsResult result = await _searchClient.IndexDocumentsAsync(batch);
                   
                }
                catch (Exception ex)
                {
                   
                }
            }
            
        }

I am using dependency injection to inject _searchClient which is an instance of type Azure.Search.Documents.SearchClient.

In my unit test project, I am mocking my SearchClient as below:

_searchClient = new Mock<SearchClient>(new Uri(endpoint),indexName, new AzureKeyCredential(key));

The problem happens when I try to setup IndexDocumentsAsync.

var indexresult = SearchModelFactory.IndexDocumentsResult;
_searchClient.Setup(x => x.IndexDocumentsAsync(batch, options, new CancellationToken())).Returns(indexresult);

When I run this code, I get a runt time error:

: 'Invalid callback. Setup on method with 3 parameter(s) cannot invoke callback with different number of parameters (1).'

I thought may be its because the last 2 params of the method IndexDocumentsAsync are optional so I tried with

_searchClient.Setup(x => x.IndexDocumentsAsync(batch)).Returns(indexresult);

With this I get a compilation issue: enter image description here

Can anyone help please?

Tarun Bhatt
  • 727
  • 2
  • 8
  • 28
  • It does not seem that the error is from this setup. Do you have another setup using `Callback(...)`? BTW: This setups should use `ReturnsAsync` instead of `Returns`. – Klaus Gütter Feb 06 '23 at 05:25
  • I tried that but facing some other compilation issues in it – Tarun Bhatt Feb 06 '23 at 05:39
  • Can u elaborate more on the Callback(...) idea? I didnt get that – Tarun Bhatt Feb 06 '23 at 05:39
  • As the error mesage complains about a bad callback, but the code you presented does not have any `Callback(...)`, I wonder if some other part of your code has. – Klaus Gütter Feb 06 '23 at 07:09
  • I have some other test cases but those are not using SeacrhClient. Instead they are using SearchIndexClient – Tarun Bhatt Feb 06 '23 at 10:28
  • you need to use the ReturnsAsync method to return a Task result from the mocked method since the IndexDocumentsAsync method returns a Task`` – Sourav Mar 09 '23 at 07:15

0 Answers0