您好我正在尝试从MongoDB中提取数据的单元测试库,并使用mongo驱动程序进行C#。
这是我要测试的代码:
var cursor = _collection.FindAs<DictionaryDocument>(Query.Exists(key)).SetFields(Fields.Include(key)).SetLimit(1);
我可以成功测试第一部分,FindAs这里是简单的测试片段:
var collection = GetMockedSettingsCollection();
collection.Setup(c => c.FindAs<DictionaryDocument>(It.IsAny<IMongoQuery>())).Returns<IMongoQuery>(s => It.IsAny<MongoCursor<DictionaryDocument>>());
var repo = new MongoSettingsRepository(new MongoStorageConfiguration<DictionaryDocument> {Collection = collection.Object});
问题是我不知道如何模拟代码的返回值,因此我之后可以设置SetFields
和SetLimit
。
任何提示?
修改 我试图像这样“链接模拟”结果:
var collection = GetMockedSettingsCollection();
var mockedFieldsCursor = new Mock<MongoCursor<DictionaryDocument>>();
var mockedLimitCursor = new Mock<MongoCursor<DictionaryDocument>>();
mockedLimitCursor.Setup(c => c.SetLimit(It.IsAny<int>()))
.Returns<IMongoQuery>(s => It.IsAny<MongoCursor<DictionaryDocument>>());
mockedFieldsCursor.Setup(c => c.SetFields(It.IsAny<IMongoFields>())).Returns<IMongoQuery>(s => mockedLimitCursor.Object);
collection.Setup(c => c.FindAs<DictionaryDocument>(It.IsAny<IMongoQuery>())).Returns<IMongoQuery>(s => mockedFieldsCursor.Object);
var repo = new MongoSettingsRepository(new MongoStorageConfiguration<DictionaryDocument> {Collection = collection.Object});
但是我收到的错误是Moq无法实例化mockedFieldsCursor.Object