问题描述
我正在使用.NET Core 2.0和.NET Core MongoDB驱动程序.
I am using .NET Core 2.0 and the .NET Core MongoDB driver.
我已经创建了一个类似这样的存储库:
I have created a repository like so:
public interface IRepository<T>
{
IMongoQueryable<T> Get()
}
我这样做是为了给使用它的人提供灵活性,使其能够像使用EF一样执行LINQ.问题是涉及单元测试时,我正在尝试创建一个内存数据库,以便我可以检查操作前后的状态.
I have done this to give flexibility to whoever uses this to be able to do LINQ much like they would do using EF. The problem is when it comes to unit testing and I'm trying to create an in-memory database so I can check states before and after operation.
我尝试过的一些东西:
public class InMemoryRepository : IRepository<ConcreteType>
{
private HashSet<ConcreteType> _data = new HashSet<ConcreteType>();
public IMongoQueryable<ConcreteType> Get()
{
return (IMongoQueryable<ConcreteType>)_data.AsQueryable();
}
}
该案例不起作用,因为IMongoQueryable
的界面是:
The case doesn't work as the interface for IMongoQueryable
is:
public interface IMongoQueryable<T> : IMongoQueryable, IQueryable, IEnumerable, IQueryable<T>, IEnumerable<T>, IAsyncCursorSource<T>
另一回合:
public class InMemoryRepository : IRepository<ConcreteType>
{
private HashSet<ConcreteType> _data = new HashSet<ConcreteType>();
public InMemoryRepository()
{
_mongoQueryableMock = new Mock<IMongoQueryable<ConcreteType>>();
_mongoQueryableMock.Setup(m => m.AsQueryable()).Returns(_data.AsQueryable);
}
public IMongoQueryable<ConcreteType> Get()
{
return _mongoQueryableMock.Object;
}
}
这不起作用,因为IMongoQueryable.AsQueryable()
是扩展方法,我无法模拟/设置它.
This doesn't work as IMongoQueryable.AsQueryable()
is an extension method and I can't mock/setup that.
推荐答案
将模拟配置为能够处理IQueryable
调用.
Configure the mock to be able to handle IQueryable
calls.
public class InMemoryRepository : IRepository<ConcreteType> {
private HashSet<ConcreteType> _data = new HashSet<ConcreteType>();
private Mock<IMongoQueryable<ConcreteType>> _mongoQueryableMock;
public ReviseMeasureRepository() {
var queryableList = _data.AsQueryable();
_mongoQueryableMock = new Mock<IMongoQueryable<ConcreteType>>();
_mongoQueryableMock.As<IQueryable<ConcreteType>>().Setup(x => x.Provider).Returns(queryableList.Provider);
_mongoQueryableMock.As<IQueryable<ConcreteType>>().Setup(x => x.Expression).Returns(queryableList.Expression);
_mongoQueryableMock.As<IQueryable<ConcreteType>>().Setup(x => x.ElementType).Returns(queryableList.ElementType);
_mongoQueryableMock.As<IQueryable<ConcreteType>>().Setup(x => x.GetEnumerator()).Returns(() => queryableList.GetEnumerator());
}
public IMongoQueryable<ConcreteType> Get() {
return _mongoQueryableMock.Object;
}
//...
}
通过这种方式,我认为存储库的设计很漏水,并将您的代码直接耦合到外部依赖项.考虑审查存储库抽象的设计.
With that out of the way I think the design of the repository is leaky and directly couples your code to external dependencies. Consider reviewing the design of the repository abstraction.
这篇关于使用IMongoQueryable进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!