From the new CosmosDb emulator I got sort of a repository to perform basic documentdb operations, this repository gets injected to other classes. I wanted to unit test a bas
The key to this is that the CreateDocumentQuery you are calling, though shown as returning IOrderedQueryable, the encapsulated result will also be derived from IDocumentQuery which is what would allow .AsDocumentQuery() to work.
Now normally you should not be mocking what you do not own. However in this case if you want to exercise ExecuteQueryAsync to completion you can create a fake abstraction that will allow the test to be exercised to completion.
The following Example shows how it can be done.
[TestClass]
public class DocumentDBRepositoryShould {
///
/// Fake IOrderedQueryable IDocumentQuery for mocking purposes
///
public interface IFakeDocumentQuery : IDocumentQuery, IOrderedQueryable {
}
[TestMethod]
public async Task ExecuteQueryAsync() {
//Arrange
var description = "BBB";
var expected = new List {
new MyDocumentClass{ Description = description },
new MyDocumentClass{ Description = "ZZZ" },
new MyDocumentClass{ Description = "AAA" },
new MyDocumentClass{ Description = "CCC" },
};
var response = new FeedResponse(expected);
var mockDocumentQuery = new Mock>();
mockDocumentQuery
.SetupSequence(_ => _.HasMoreResults)
.Returns(true)
.Returns(false);
mockDocumentQuery
.Setup(_ => _.ExecuteNextAsync(It.IsAny()))
.ReturnsAsync(response);
var client = new Mock();
client
.Setup(_ => _.CreateDocumentQuery(It.IsAny(), It.IsAny()))
.Returns(mockDocumentQuery.Object);
var cosmosDatabase = string.Empty;
var documentsRepository = new DocumentDBRepository(cosmosDatabase, client.Object);
//Act
var query = documentsRepository.GetQueryable(); //Simple query.
var actual = await documentsRepository.ExecuteQueryAsync(query);
//Assert
actual.Should().BeEquivalentTo(expected);
}
}