I am writing unit tests for below piece of code which is using Document client CreateDocumentQuery method with where(filter) conditions.
var documentQuery = ReadOnlyDocumentClient.CreateDocumentQuery<MyView>(UriFactory.CreateDocumentCollectionUri(Constants.COSMOS_DB_NAME, Constants.MY_VIEW_COL_NAME))
.Where(w => w.Name== query.Name)
.Where(w => w.DOB> query.StartDate && w.DOB < query.EndDate)
.AsDocumentQuery();
query is a command parameter which is an input.
I am using MOQ to mock and I am using below code line to mock
mockDocumentClient.Setup(s => s.CreateDocumentQuery<MyView>(It.IsAny<Uri>(), It.IsAny<FeedOptions>())).Returns(mockDocumentQuery.Object);
Now, above piece of code only mocks CreateDocumentQuery and when Where conditions are executed I am not getting mock support.
Please suggest how can I mock CreateDocumentQuery with where conditions?
Thanks in advance.
When you mock the CreateDocumentQuery
, you also need to mock the IQueryProvider
which interacts with the IEnumerable
that you expect as the result of the query.
Here's an example:
// somewhere in your test class
public interface IFakeDocumentQuery<T> : IDocumentQuery<T>, IOrderedQueryable<T>
{
}
// somewhere in your test method
var expected = new List<YourType>
{
new YourType
{
yourField = "yourValue"
}
};
var mockDocumentClient = new Mock<IDocumentClient>();
var dataSource = expected.AsQueryable();
var response = new FeedResponse<YourType>(dataSource);
var mockDocumentQuery = new Mock<IFakeDocumentQuery<YourType>>();
// the part that gets the work done :)
var provider = new Mock<IQueryProvider>();
provider
.Setup(p => p.CreateQuery<YourType>(It.IsAny<Expression>()))
.Returns(mockDocumentQuery.Object);
mockDocumentQuery
.Setup(q => q.ExecuteNextAsync<YourType>(It.IsAny<CancellationToken>()))
.ReturnsAsync(response);
mockDocumentQuery
.SetupSequence(q => q.HasMoreResults)
.Returns(true)
.Returns(false);
mockDocumentQuery
.As<IQueryable<YourType>>()
.Setup(x => x.Provider)
.Returns(provider.Object);
mockDocumentQuery
.As<IQueryable<YourType>>()
.Setup(x => x.Expression)
.Returns(dataSource.Expression);
mockDocumentQuery
.As<IQueryable<YourType>>()
.Setup(x => x.ElementType)
.Returns(dataSource.ElementType);
mockDocumentQuery
.As<IQueryable<YourType>>()
.Setup(x => x.GetEnumerator())
.Returns(dataSource.GetEnumerator);
mockDocumentClient
.Setup(c => c.CreateDocumentQuery<YourType>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
.Returns(mockDocumentQuery.Object);
I hope that helps! :)
You can try following example:
var documentClientMock = new Mock<IDocumentClient>();
var docs = new List<MyView>();//your mock data
documentClientMock.Setup(d => d.CreateDocumentQuery<MyView>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
.Returns((IOrderedQueryable<MyView>) docs.AsQueryable());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With