How to mock IFindFluent interface

…衆ロ難τιáo~ 提交于 2020-01-24 11:28:46

问题


I am writing unit tests with mongo db and I need to test somehow methods that works with data returned from mongo. For example method

IFindFluent<Transcript, Transcript> GetTranscriptByUserId(int userId);

Should return some transcript. But instead it returns interface that has couple of props - Filter, Options, Sort, and other.

I am going to test method Paginane of Paginator<T> class

public PaginatedObject<T> Paginate(IFindFluent<T,T> items, int limit, int page)
{
    if (limit == 0)
    {
        limit = 10;
    }

    int count = (int)items.Count();
    var lastPage = (count / limit) + 1;
    if (page <= 0)
    {
        page = 1;
    }

    if (page > lastPage)
    {
        page = lastPage;
    }

    var request = items.Skip((page - 1) * limit).Limit(limit);
    var itemsToReturn = request.ToList();

    var pages = new PaginatedObject<T>
    {
        Entries = itemsToReturn,
        Limit = limit,
        Total = count,
        Page = page
    };

    return pages;
}

First param is interface IFindFluent<T,T> items. So, I should mock it to return items when I call Count, Skip and Limit. But these methods could be easily mocked.

mockIfindFluent = new Mock<IFindFluent<Transcript, Transcript>>();

mockIfindFluent.Setup(s => s.Limit(It.IsAny<int>())).Returns(mockIfindFluent.Object);
mockIfindFluent.Setup(i => i.Skip(It.IsAny<int>())).Returns(mockIfindFluent.Object);
mockIfindFluent.Setup(i => i.Count(CancellationToken.None)).Returns(3);

Real problem I have when I call ToList().

I got exception that I can not mock property that does not belong to model and so on.


回答1:


Took some inspiration from this https://gist.github.com/mizrael/a061331ff5849bf03bf2 and extended implementation which worked for me. I have created a fake implementation of the IFindFluent interface and it had a dependency on the IAsyncCursor interface, so I did a fake implementation of that also and using that in return of mock method I wanted to set up. In that fake implementation, I have initialized an enumerable and returned that in a method I am using. You can still be more creative and play around whatever you want to return. So far this worked for me.

Here is a fake implementation.

public class FakeFindFluent<TEntity, TProjection> : IFindFluent<TEntity, TEntity>
{
    private readonly IEnumerable<TEntity> _items;

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

    public FilterDefinition<TEntity> Filter { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public FindOptions<TEntity, TEntity> Options => throw new NotImplementedException();

    public IFindFluent<TEntity, TResult> As<TResult>(MongoDB.Bson.Serialization.IBsonSerializer<TResult> resultSerializer = null)
    {
        throw new NotImplementedException();
    }

    public long Count(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public Task<long> CountAsync(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public long CountDocuments(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public Task<long> CountDocumentsAsync(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public IFindFluent<TEntity, TEntity> Limit(int? limit)
    {
        throw new NotImplementedException();
    }

    public IFindFluent<TEntity, TNewProjection> Project<TNewProjection>(ProjectionDefinition<TEntity, TNewProjection> projection)
    {
        throw new NotImplementedException();
    }

    public IFindFluent<TEntity, TEntity> Skip(int? skip)
    {
        throw new NotImplementedException();
    }

    public IFindFluent<TEntity, TEntity> Sort(SortDefinition<TEntity> sort)
    {
        throw new NotImplementedException();
    }

    public IAsyncCursor<TEntity> ToCursor(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

    public Task<IAsyncCursor<TEntity>> ToCursorAsync(CancellationToken cancellationToken = default)
    {
        IAsyncCursor<TEntity> cursor = new FakeAsyncCursor<TEntity>(_items);
        var task = Task.FromResult(cursor);

        return task;
    }
}


public class FakeAsyncCursor<TEntity> : IAsyncCursor<TEntity>
{
    private IEnumerable<TEntity> items;

    public FakeAsyncCursor(IEnumerable<TEntity> items)
    {
        this.items = items;
    }

    public IEnumerable<TEntity> Current => items;

    public void Dispose()
    {
        //throw new NotImplementedException();
    }

    public bool MoveNext(CancellationToken cancellationToken = default)
    {
        throw new NotImplementedException();
    }

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

Here is how I set up my mock method to return what I wanted for my unit testing.

mockParticipantRepository
                .Setup(x => x.FindByFilter(It.IsAny<FilterDefinition<Participant>>()))
                .Returns(new FakeFindFluent<Participant, Participant>(participantsByRelation));

I hope this is helpful.



来源:https://stackoverflow.com/questions/43203657/how-to-mock-ifindfluent-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!