我正在尝试为使用MongoDb 2.0.1驱动程序的存储库层编写单元测试。
我有ImongoCollection的依赖。
有人知道如何模拟避免使用真正的数据库吗? 谢谢
以下是代码:
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();
}
}
我尝试像
一样 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();
}