[英]Mocking MongoDb Methods such as Find,FindAsync Method in Xunit
我正在嘗試模擬 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));
當我在網上沖浪時,它所說的擴展方法不能被模擬,上面的方法[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
}
實例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);
//...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.