返回IAsyncCursor的MongoDB C#驱动程序Mock方法

joa*_*eza 4 c# unit-testing moq mongodb mongodb-.net-driver

我正在为使用mongoDB c#驱动程序的DAL创建一些单元测试。问题是我有要测试的方法:

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

并使用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>);
Run Code Online (Sandbox Code Playgroud)

但是,如果expectedEntities as IAsyncCursor<Entity>为null,则测试无法正常工作。

模拟此方法并处理IAsyncCursor的最佳方法是什么?

Nko*_*osi 7

模拟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.
Run Code Online (Sandbox Code Playgroud)

有关如何枚举光标的参考,请查看此答案。

IAsyncCursor如何与mongodb c#驱动程序一起用于迭代?

在此之后,您将能够理解为什么为移动下一个方法的序列设置了模拟程序。


Ste*_*eve 6

如果它对其他人有帮助.... 在@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()
    {
    }
}


Run Code Online (Sandbox Code Playgroud)