在使用SQL查询的单元测试中模拟IDocumentQuery

时间:2018-04-20 06:59:46

标签: c# unit-testing azure moq azure-cosmosdb

我正在使用单元测试来测试DocumentDBRepository类。我跟着this post作为SQL查询用例的示例。但它显示错误

  

消息:System.InvalidCastException:无法转换类型的对象   “System.Linq.EnumerableQuery   输入   “Microsoft.Azure.Documents.Linq.IDocumentQuery

这是我的DocumentDBRepository

的代码
private IDocumentQuery<T> GetQueryBySQL(string queryStr)
{
    var uri = UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId);
    var feedOptions = new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true };
    IQueryable<T> filter = _client.CreateDocumentQuery<T>(uri, queryStr, feedOptions); 
    IDocumentQuery<T> query = filter.AsDocumentQuery();
    return query;

}

public async Task<IEnumerable<T>> RunQueryAsync(string queryString)
{
    IDocumentQuery<T> query = GetQueryBySQL(queryString);

    List<T> results = new List<T>();

    while (query.HasMoreResults)
    {
        results.AddRange(await query.ExecuteNextAsync<T>());
    }
    return results;
}

这是我的测试类的代码

public async virtual Task Test_GetEntitiesAsyncBySQL()
{
    var id = "100";
    string queryString = "SELECT * FROM c WHERE c.ID = " + id;
    var dataSource = new List<Book> {
            new Book { ID = "100", Title = "abc"}}.AsQueryable();


    Expression<Func<Book, bool>> predicate = t => t.ID == id;
    var expected = dataSource.Where(predicate.Compile());
    var response = new FeedResponse<Book>(expected);

    var mockDocumentQuery = new Mock<DocumentDBRepositoryTest.IFakeDocumentQuery<Book>>();

    mockDocumentQuery
        .SetupSequence(_ => _.HasMoreResults)
        .Returns(true)
        .Returns(false);

    mockDocumentQuery
        .Setup(_ => _.ExecuteNextAsync<Book>(It.IsAny<CancellationToken>()))
        .ReturnsAsync(response);

    var provider = new Mock<IQueryProvider>();
    provider
        .Setup(_ => _.CreateQuery<Book>(It.IsAny<Expression>()))
        .Returns(mockDocumentQuery.Object);

    mockDocumentQuery.As<IQueryable<Book>>().Setup(x => x.Provider).Returns(provider.Object);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(x => x.Expression).Returns(dataSource.Expression);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(x => x.ElementType).Returns(dataSource.ElementType);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(x => x.GetEnumerator()).Returns(() => dataSource.GetEnumerator());

    var client = new Mock<IDocumentClient>();

    client.Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
          .Returns(mockDocumentQuery.Object);

    var documentsRepository = new DocumentDBRepository<Book>(client.Object, "100", "100");

    //Act
    var entities = await documentsRepository.RunQueryAsync(queryString);

    //Assert
    entities.Should()
        .NotBeNullOrEmpty()
        .And.BeEquivalentTo(expected);
}

断点在此行代码处停止:

IQueryable<T> filter = _client.CreateDocumentQuery<T>(uri, queryStr, feedOptions); 

filter变量在很多属性上显示空异常,结果视图显示为空,当它应该显示我在测试方法中定义的expected值时。

有任何线索如何解决?

3 个答案:

答案 0 :(得分:2)

需要在模拟的客户端上设置正确的CreateDocumentQuery重载。

测试方法使用

IQueryable<T> filter = _client.CreateDocumentQuery<T>(uri, queryStr, feedOptions); 

然而,在安排测试时,客户端设置为

client
    .Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
    .Returns(mockDocumentQuery.Object);

应该改为

client
    .Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<string>(), It.IsAny<FeedOptions>()))
    .Returns(mockDocumentQuery.Object);

由于额外的queryStr参数。它也可以直接使用字符串参数作为替代,因为它被明确地注入到方法中并且可以用作期望的一部分。

client
    .Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), queryStr, It.IsAny<FeedOptions>()))
    .Returns(mockDocumentQuery.Object);

由于测试中的方法在构建查询时没有直接使用Linq,因此无需像在本主题的上一次迭代中那样模拟/覆盖查询提供程序

以上是上述变更后的完成测试

public async virtual Task Test_GetEntitiesAsyncBySQL() {
    //Arrange
    var id = "100";
    string queryString = "SELECT * FROM c WHERE c.ID = " + id;
    var dataSource = new List<Book> {
        new Book { ID = "100", Title = "abc"}
    }.AsQueryable();

    Expression<Func<Book, bool>> predicate = t => t.ID == id;
    var expected = dataSource.Where(predicate.Compile());
    var response = new FeedResponse<Book>(expected);

    var mockDocumentQuery = new Mock<IFakeDocumentQuery<Book>>();

    mockDocumentQuery
        .SetupSequence(_ => _.HasMoreResults)
        .Returns(true)
        .Returns(false);

    mockDocumentQuery
        .Setup(_ => _.ExecuteNextAsync<Book>(It.IsAny<CancellationToken>()))
        .ReturnsAsync(response);

    //Note the change here
    mockDocumentQuery.As<IQueryable<Book>>().Setup(_ => _.Provider).Returns(dataSource.Provider);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(_ => _.Expression).Returns(dataSource.Expression);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(_ => _.ElementType).Returns(dataSource.ElementType);
    mockDocumentQuery.As<IQueryable<Book>>().Setup(_ => _.GetEnumerator()).Returns(() => dataSource.GetEnumerator());

    var client = new Mock<IDocumentClient>();

    //Note the change here
    client
        .Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<string>(), It.IsAny<FeedOptions>()))
        .Returns(mockDocumentQuery.Object);

    var documentsRepository = new DocumentDBRepository<Book>(client.Object, "100", "100");

    //Act
    var entities = await documentsRepository.RunQueryAsync(queryString);

    //Assert
    entities.Should()
        .NotBeNullOrEmpty()
        .And.BeEquivalentTo(expected);
}

答案 1 :(得分:1)

您看到错误的原因对我来说似乎很简单。

以下是设置参数列表的方法 -

client.Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<FeedOptions>()))
      .Returns(mockDocumentQuery.Object);

以下是调用CreateDocumentQuery的方法 -

IQueryable<T> filter = _client.CreateDocumentQuery<T>(uri, queryStr, feedOptions);

所以基本上你错过了queryString 。这是你应该做的 -

client.Setup(_ => _.CreateDocumentQuery<Book>(It.IsAny<Uri>(), It.IsAny<string>(), It.IsAny<FeedOptions>()))
              .Returns(mockDocumentQuery.Object);

答案 2 :(得分:0)

出于某种原因, Nkosi 建议的解决方案对我不起作用(即使从逻辑上来说似乎是正确的)。请注意,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);