我正在使用moq模拟asp.net核心项目中的对象。
我要模拟以下isconnection()方法:
public Client(IMongoClient client)
{
_client = client;
}
public async Task<bool> IsConectionOk()
{
var pingCommand = new BsonDocument("ping", 1);
var mongoDb = _client.GetDatabase("Name");
var commandResult = await mongoDb.RunCommandAsync<BsonDocument>(pingCommand);
return commandResult != null;
}
如你所见,只有一次注射,
IMongoClient
,所以我需要模仿这一次。现在,我还需要模拟IMongoDatabase
,因为_client.GetDatabase
返回一个IMongoDatabase
,它运行RunCommandAsync
这是我的单元测试:
[Fact]
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<BsonDocument>(), It.IsAny<ReadPreference>(), It.IsAny<CancellationToken>())).ReturnsAsync(resultCommand);
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
await client.IsConectionOk();
//assert
dbMock.Verify(mock => mock.RunCommandAsync<BsonDocument>( It.Is<BsonDocument>(x => x.Equals(pingCommand)) , It.IsAny<ReadPreference>() ,It.IsAny<CancellationToken>()));
}
你可以看到我模仿了一个
IMongoDatabase
,所以我的mongoClientMock
可以在代码执行时返回它。当代码运行时,我检查了mongoClientMock.GetDatabase()
是否返回了MongoDatabase
(直到返回时为止是好的),问题是当MongoDatabaseMock
调用runcommandasync时没有返回我设置的内容,它只返回空值。我不知道我会错过什么,有什么想法吗? 最佳答案
这里的事情有点棘手。
先看看背景。
根据文件,IMongoDatabase.RunCommandAsync<TResult>
定义为
Task<TResult> RunCommandAsync<TResult>(
Command<TResult> command,
ReadPreference readPreference = null,
CancellationToken cancellationToken = null
)
请注意
Command<TResult>
,而在您的代码中,您传递的是BsonDocument
。幸运的是
BsonDocument
有一个从BsonDocument
到Command<TResult>
的隐式转换运算符。当安装程序没有得到配置的内容时,它往往返回空值。因此,您需要确保它的设置正确,以便它执行预期的行为。
[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();
}
}