小编sam*_*606的帖子

Mocking MongoDb 方法,例如 Xunit 中的 Find、FindAsync 方法

我正在尝试模拟 mongodb 的 findasync,在 Xunit 和 .net 核心中查找方法。

当我试图模拟 InsertOne 时,

mockcollection.setup(x=>x.InsertOneAsync(_newitem,null,It.IsAny<CancellationToken>()).Returns(task.CompletedTask);

but the find is throwing error "Extension Method FindAsync may not be used in setup/verify process.

mockcollection.setup(x=>x.FindAsync(It.IsAny<FilterDefinition<mytbl>>(),null,It.IsAny<CancellationToken>()).Returns(Task.FromResult(mockasyncursor.Object));

Run Code Online (Sandbox Code Playgroud)

当我在网上冲浪时,它说的是扩展方法不能被模拟,上面的方法[FindAsync]是一个扩展方法,其中作为InsertOne并非如此。

我如何模拟该findasync方法?

注意:我尝试使用Mongo2go模拟数据库并能够得出积极的结果,但想知道如何使用模拟?

方法:

public async Task<IEnumerable<XX>> abc()
{
_logger.LogInformation("XXX");

var result = _context
        .XX.FindAsync(_ => true, null, CancellationToken.None);

return ( await _context.XX.FindAsync(_ => true) ).ToList<XX>();
}
Run Code Online (Sandbox Code Playgroud)

单元测试方法:

public async Task XXX()
{
    // Arrange
    var XX = this.XX();
                < IAsyncCursor < XX …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq xunit mongodb

1
推荐指数
1
解决办法
1999
查看次数

标签 统计

c# ×1

mongodb ×1

moq ×1

unit-testing ×1

xunit ×1