我正在尝试在Xunit和.net核心中模拟mongodb的findasync,find方法。
当我尝试模拟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));
当我在网上冲浪时,只能说扩展方法不能被模仿,上面的方法[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>();
}
单元测试方法:
public async Task XXX()
{
// Arrange
var XX = this.XX();
< IAsyncCursor < XX >> mockasynccursor = new Mock<IAsyncCursor<XX>>();
mockXXCollection = new Mock<IMongoCollection<XX>>();
mockasynccursor.Setup(_ => _.Current).Returns(ReadfromJson());
mockasynccursor.
SetupSequence
(_ => _.MoveNext(It.IsAny<CancellationToken>())).Returns(true).Returns(false);
//sample
var newitem = new XX { };
mockXXCollection.
Setup(x => x.InsertOneAsync(newitem, null, default(CancellationToken)))
.Returns(Task.CompletedTask);
//Error Here
mockXXCollection.Setup(x => x.FindAsync(It.IsAny<FilterDefinition<XX>>(), null, CancellationToken.None))
.Returns(Task.FromResult(mockasynccursor.Object));
//Message: System.NotSupportedException : Unsupported expression: x => x.FindAsync<XX>(It.IsAny<FilterDefinition<XX>>(), null, CancellationToken.None)
//Extension methods( here: IMongoCollectionExtensions.FindAsync) may not be used in setup / verification expressions.
mockStateFormContext.Setup(x => x.StateForms).Returns(mockXXCollection.Object);
// Act
var result = await xyzRepository.abc();
// Assert
}
答案 0 :(得分:1)
实例FindAsync
的定义如下:
Task<IAsyncCursor<TProjection>> FindAsync<TProjection>(
FilterDefinition<TDocument> filter,
FindOptions<TDocument, TProjection> options = null,
CancellationToken cancellationToken = null
)
所有扩展方法最终都会回调该成员。
在配置模拟时,请确保已明确设置实例成员
//...
mockXXCollection
.Setup(_ => _.FindAsync(
It.IsAny<FilterDefinition<XX>>(),
It.IsAny<FindOptions<XX, XX>>(),
It.IsAny<CancellationToken>()
))
.ReturnsAsync(mockasynccursor.Object);
//...