如何用DocumentDb单元测试的过滤器模拟DocumentClient CreateDocumentQuery?

时间:2018-06-17 13:31:30

标签: c# unit-testing documentclient

我正在为下面的代码编写单元测试,该代码使用Document客户端CreateDocumentQuery方法和where(filter)条件。

 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是一个命令参数,它是一个输入。

我使用MOQ进行模拟,我使用下面的代码行来模拟

 mockDocumentClient.Setup(s => s.CreateDocumentQuery<MyView>(It.IsAny<Uri>(), It.IsAny<FeedOptions>())).Returns(mockDocumentQuery.Object);

现在,上面的代码只是模拟CreateDocumentQuery,当执行Where条件时,我没有得到模拟支持。

请建议如何使用where条件模拟CreateDocumentQuery?

提前致谢。

2 个答案:

答案 0 :(得分:1)

模拟CreateDocumentQuery时,还需要模拟IQueryProvider,该IEnumerable与查询所期望的 // 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); 交互。

这是一个例子:

{{1}}

希望对您有所帮助! :)

答案 1 :(得分:1)

您可以尝试以下示例:

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());