簡體   English   中英

MongoDB C#驅動程序Mock方法返回IAsyncCursor

[英]MongoDB C# driver Mock method that returns IAsyncCursor

我正在為使用mongoDB c#驅動程序的DAL創建一些單元測試。 問題是我有這個方法,我想測試:

    public async virtual Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> predicate)
    {
        return (await Collection.FindAsync(predicate)).ToList();
    }

並使用Moq我已經模仿了這樣的集合:

var mockMongoCollectionAdapter = new Mock<IMongoCollectionAdapter<Entity>>();

var expectedEntities = new List<Entity>
{
    mockEntity1.Object,
    mockEntity2.Object
};

mockMongoCollectionAdapter.Setup(x => x.FindAsync(It.IsAny<Expression<Func<Entity,bool>>>(), null, default(CancellationToken))).ReturnsAsync(expectedEntities as IAsyncCursor<Entity>);

但是由於expectedEntities as IAsyncCursor<Entity>為空,因此測試不起作用。

模擬此方法並處理IAsyncCursor的最佳方法是什么?

模擬IAsyncCursor<TDocument> interface以便枚舉它。 接口上的方法沒有多少

var mockCursor = new Mock<IAsyncCursor<Entity>>();
mockCursor.Setup(_ => _.Current).Returns(expectedEntities); //<-- Note the entities here
mockCursor
    .SetupSequence(_ => _.MoveNext(It.IsAny<CancellationToken>()))
    .Returns(true)
    .Returns(false);
mockCursor
    .SetupSequence(_ => _.MoveNextAsync(It.IsAny<CancellationToken>()))
    .Returns(Task.FromResult(true))
    .Returns(Task.FromResult(false));

mockMongoCollectionAdapter
    .Setup(x => x.FindAsync(
            It.IsAny<Expression<Func<Entity, bool>>>(),
            null,
            It.IsAny<CancellationToken>()
        ))
    .ReturnsAsync(mockCursor.Object); //<-- return the cursor here.

有關如何枚舉光標的參考,請查看此答案。

IAsyncCursor如何用於mongodb c#驅動程序的迭代?

在此之后,您將能夠理解為什么模擬設置了移動下一個方法的序列。

如果它幫助其他人......在@Nkosi嘲笑的答案之后,我實現了以下課程

public class MockAsyncCursor<T> : IAsyncCursor<T>
{
    private readonly IEnumerable<T> _items;
    private bool called = false;

    public MockAsyncCursor(IEnumerable<T> items)
    {
        _items = items ?? Enumerable.Empty<T>();
    }

    public IEnumerable<T> Current => _items;

    public bool MoveNext(CancellationToken cancellationToken = new CancellationToken())
    {
        return !called && (called = true);
    }

    public Task<bool> MoveNextAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult(MoveNext(cancellationToken));
    }

    public void Dispose()
    {
    }
}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM