Mock ImongoCollection Driver 2.0.1 C #

I am trying to write a unit test for my repository layer that uses MongoDb 2.0.1 driver.

I have a dependency ImongoCollection.

Does anyone know how to mock it to avoid using a real db? Thanks you

Below is the code:

public class Repository<T> : IRepository<T>
    where T : Content
{
    private readonly IMongoCollection<T> _mongoCollection;
    public Repository(IMongoCollection<T> mongoCollection)
    {
        _mongoCollection = mongoCollection;
    }

    public void Insert(T entity)
    {
        _mongoCollection.InsertOneAsync(entity);
    }

    public async void Update(T entity)
    {
        await _mongoCollection.InsertOneAsync(entity);
    }

    public async void Delete(string id)
    {
        await _mongoCollection.DeleteOneAsync(Builders<T>.Filter.Where(x => x.Id == id));
    }

    public async Task<T> GetById(string id)
    {
        return await _mongoCollection.Find(Builders<T>.Filter.Where(x => x.Id == id)).FirstOrDefaultAsync();
    }

    /// <summary>
    /// This method will retrieve a list of items 
    /// by passing a dynamic mongo query
    /// Eg. AND - var filter =  builder.Eq("cuisine", "Italian") & builder.Eq("address.zipcode", "10075");
    /// Eg. OR - var filter =  builder.Eq("cuisine", "Italian") | builder.Eq("address.zipcode", "10075");
    /// </summary>
    /// <param name="filter"></param>
    /// <returns></returns>
    public async Task<List<T>> GetByFilter(FilterDefinition<T> filter)
    {
        filter = filter ?? new BsonDocument();
        return await _mongoCollection.Find(filter).ToListAsync();
    }


    public async Task<List<T>> GetAll()
    {
        return await _mongoCollection.Find(new BsonDocument()).ToListAsync();
    }
}

      

I am trying to do something like

    private Mock<IMongoCollection<Content>> _mockContentCollection;
    private IRepository<Content> _contentRepository;

    [SetUp]
    public void TestMethod1()
    {
        _mockContentCollection = new Mock<IMongoCollection<Content>>();
        _mockContentCollection.Setup(x => x.)....

        _contentRepository = new Repository<Content>(_mockContentCollection.Object);
    }

    [Test]
    public void GetAll_With_Results()
    {
        var a = _contentRepository.GetAll();
    }

      

+3


source to share





All Articles