C# 如何模拟IMONGO数据库

C# 如何模拟IMONGO数据库,c#,mongodb,unit-testing,moq,C#,Mongodb,Unit Testing,Moq,我正在使用Moq模拟ASP.NET核心项目中的对象 我想模拟以下IsConnection()方法: 您可以看到,我模拟了一个IMongoDatabase,因此我的mongoClientMock可以在代码执行时返回它。当代码运行时,我检查了mongoClientMock.GetDatabase()是否返回了MongoDatabase(在这之前还不错),问题是MongoDatabaseMock调用RunCommandAsync时没有返回我设置的内容,它只返回null。我不知道我可能会错过什么,有什么

我正在使用Moq模拟ASP.NET核心项目中的对象

我想模拟以下IsConnection()方法:


您可以看到,我模拟了一个
IMongoDatabase
,因此我的
mongoClientMock
可以在代码执行时返回它。当代码运行时,我检查了
mongoClientMock.GetDatabase()
是否返回了
MongoDatabase
(在这之前还不错),问题是
MongoDatabaseMock
调用RunCommandAsync时没有返回我设置的内容,它只返回null。我不知道我可能会错过什么,有什么想法吗?

刚刚发现我的问题,请看下一行:

dbMock.Setup(stub => stub.RunCommandAsync<BsonDocument>(It.IsAny<BsonDocument>(), It.IsAny<ReadPreference>(), It.IsAny<CancellationToken>())).ReturnsAsync(resultCommand);

问题解决了

这里的事情有点棘手

首先是一些背景知识

根据文档,
IMongoDatabase.RunCommandAsync
被定义为

Task<TResult> RunCommandAsync<TResult>(
    Command<TResult> command,
    ReadPreference readPreference = null,
    CancellationToken cancellationToken = null
)

验证也不起作用,因为它们有不同的实例。@Nkosi另外,你说的“验证不起作用”是什么意思?我的mongoClientMock.GetDatabase()应该返回在测试开始时设置的dbMock,因此它是同一个实例,我是否缺少什么?您可以在测试方法之外初始化一个命令,并尝试验证它(实例)是否在模拟中使用。验证将失败。您实际上在测试的方法中测试和验证的是什么?@Nkosi我刚刚再次编辑,IsConnection()方法检查resultCommand是否为null,因此首先,我需要模拟MongoDatabase并设置RunCommandAsync方法,以便我的测试通过。我的全部目标是检查RunCommandAsync是否使用pingCommand调用
dbMock.Setup(stub => stub.RunCommandAsync<BsonDocument>(It.IsAny<BsonDocument>(), It.IsAny<ReadPreference>(), It.IsAny<CancellationToken>())).ReturnsAsync(resultCommand);
dbMock.Setup(stub => stub.RunCommandAsync<BsonDocument>(It.IsAny<Command<BsonDocument>>(), It.IsAny<ReadPreference>(), It.IsAny<CancellationToken>())).ReturnsAsync(anyResultCommand);
Task<TResult> RunCommandAsync<TResult>(
    Command<TResult> command,
    ReadPreference readPreference = null,
    CancellationToken cancellationToken = null
)
[TestClass]
public class UnitTest1 {
    [TestMethod]
    public async Task _IsConnectionOk_xxx_RunPing1Command() {
        var dbMock = new Mock<IMongoDatabase>();
        var resultCommand = new BsonDocument("ok", 1);
        dbMock
            .Setup(stub => stub.RunCommandAsync<BsonDocument>(It.IsAny<Command<BsonDocument>>(), It.IsAny<ReadPreference>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync(resultCommand)
            .Verifiable();

        var mongoClientMock = new Mock<IMongoClient>();
        mongoClientMock
            .Setup(stub => stub.GetDatabase(It.IsAny<string>(), It.IsAny<MongoDatabaseSettings>()))
            .Returns(dbMock.Object);

        var client = new Client(mongoClientMock.Object);
        var pingCommand = new BsonDocument("ping", 1);

        //act
        var actual = await client.IsConectionOk();

        //assert
        Assert.IsTrue(actual);
        dbMock.Verify();
    }
}