Unit test of QueryAsync method

Below is code snippet
ICluster cluster = await _bucketFactory.GetClusterAsync();
IQueryResult result = await cluster.QueryAsync(query, usedQueryOptions);
await foreach (var row in result.Rows)
{
var rowValue = row;
if (row.id == null) continue;
searchResults.Add((string)row.id);
}

    return searchResults;

I am using nunit for test case
Snippet of unit test

    Mock<IQueryResult<object>> queryResultMock = new Mock<IQueryResult<object>>();

    queryResultMock.Setup(m => m.Rows).Returns(rowsList.ToAsyncEnumerable());
    
    // Set up the behavior of the cluster mock
    _clustertMock.Setup(c => c.QueryAsync<dynamic>(It.IsAny<string>(), It.IsAny<QueryOptions>()))
        .ReturnsAsync(queryResultMock.Object);
    
   
    // Inject the mocked cluster into the _bucketFactory
    _mockDocStoreSdkBucketFactory.Setup(b => b.GetClusterAsync())
        .ReturnsAsync(_clustertMock.Object);
    
    // Act
    List<string> actualResults = await GetN1qlQueryService().SearchExecuteQueryWithRetryReturnStrings(query, _bucketMock.Object);

    // Assert
    Assert.AreEqual(1, actualResults.Count);

I am able to get value in IQueryResult result but getting null exception for foreach condition.
Not sure hoe can i mock QueryAsync to avoid this error.

but getting null exception for foreach condition .

There are two places where you could get a null exception - where row.id is referenced and where searchResult.Add is referenced. So it would appear that one of them is null.

I had provided wrong foreach condition, actual condition is

ICluster cluster = await _bucketFactory.GetClusterAsync();
IQueryResult result = await cluster.QueryAsync(query, usedQueryOptions);
await foreach (var row in result)
{
var rowValue = row;
if (row.id == null) continue;
searchResults.Add((string)row.id);
}
return searchResults;

It would seem that searchResults is null.

Any idea how can I mock QueryAsync to get desired IQueryResult? So that I can iterate through foreach loop.

If searchResults is null then searchResults.Add is going to give a null pointer, right?
So the only way to avoid that with queryResultMock is (1) not have any rows in queryResultMock; or (2) all the rows have id == null.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.