简体   繁体   English

如何使用 XUnit 在 Cosmos DB 中对 LINQ 查询进行单元测试

[英]How to unit test the LINQ queries in Cosmos DB using XUnit

    public async Task<List<Group>?> GetInfosforGroupIdAsync(string groupId)
    {
           Container? cosmosContainer =
           await database.CreateContainerIfNotExistsAsync("Group", "/GroupId");
           if (groupId == null)
              return null;
                
           var query = cosmosContainer.GetItemLinqQueryable<Group>()
                    .Where(d => d.GroupId == groupId);
           var queryResult = query.ToFeedIterator();
           if (queryResult.HasMoreResults)
           {
               FeedResponse<Group> currentResultSet = await queryResult.ReadNextAsync();
               List<DedupeGroup> result = currentResultSet.ToList<Group>();
               return result;
           }
           return null;
   }

How can I write units tests for the above method using xunit tests.如何使用xunit测试为上述方法编写单元测试。 Assume Group is like below假设Group如下

class Group{
  string GroupId;
  string GroupInfo;
}

That's generally not a good idea.这通常不是一个好主意。 If you really wanted to unit test the method as shown, you would need to create mockups of all the used Cosmos DB classes.如果您真的想对所示方法进行单元测试,则需要创建所有使用的 Cosmos DB 类的模型。 This would be a lot of code for little value in return (or even negative net value since tests have to be maintained, may contain bugs etc.).这将是很多代码,但回报很少(甚至是负净值,因为必须维护测试,可能包含错误等)。 But that's not the biggest problem.但这还不是最大的问题。

You could factor out the thing that you actually want to unit test and only test that, namely the LINQ expression.你可以把你真正想要单元测试的东西分解出来,只测试它,即 LINQ 表达式。 You could test the IQueryable by mocking it with a normal in-memory IEnumerable .您可以使用普通的内存中IEnumerable通过 mocking 测试IQueryable But that doesn't actually work in general because LINQ queries on an IEnumerable don't behave like LINQ queries against Cosmos DB.但这实际上通常不起作用,因为IEnumerable上的 LINQ 查询的行为与针对 Cosmos DB 的 LINQ 查询不同。 For example, the null-coalesce operator in C# ( ?? ) is translated into an undefined-coalesce operator in Cosmos DB ( ?? ), or you can access non-existing keys using an indexer in Cosmos DB without error ( c['foo'] ) but you get a KeyNotFoundException in-memory.例如,C# ( ?? ) 中的 null-coalesce 运算符被转换为 Cosmos DB ( ?? ) 中的 undefined-coalesce 运算符,或者您可以使用 Cosmos DB 中的索引器访问不存在的键而不会出现错误 ( c['foo'] ),但您会在内存中获得KeyNotFoundException

Unfortunately, there is no in-memory mock CosmosClient avaiable at the moment.不幸的是,目前没有可用的内存模拟CosmosClient So you would have to write your own LINQ provider that interprets LINQ queries exactly like Cosmos DB does, but in-memory, which would be a lot of work for very little value in return.因此,您必须编写自己的 LINQ 提供程序来解释 LINQ 查询,就像Cosmos DB 所做的那样,但是在内存中,这将是很多工作,但回报很少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM