快速信息:我正在使用 C# 4.0 和 RhinoMocks(具有 AAA)
我将用一些代码来解释我正在考虑做什么:
public class SampleData
{
private List<Person> _persons = new List<Person>()
{
new Person { PersonID = 1, Name = "Jack"},
new Person { PersonID = 2, Name = "John"}
};
public List<Person> Persons
{
get { return _persons; }
}
}
所以这是一个模拟数据库中数据的类。现在我想在我的单元测试中使用这些数据。换句话说,我不想从数据库中获取数据,而是想从数据存储库中获取数据。
我认为我可以通过 stub 存储库并使其使用 DataRepository 来实现这一点:
UC1003_ConsultantsBeherenBL consultantsBeherenBL = new UC1003_ConsultantsBeherenBL();
consultantsBeherenBL = MockRepository.GeneratePartialMock<UC1003_ConsultantsBeherenBL>();
consultantsBeherenBL.Repository = MockRepository.GenerateMock<IRepository>();
这会导致我的代码改为自动在 DataRepository 中查找数据。因此,不是 stub 方法并直接插入列表(例如 d => d.Find(Arg.Is.Anything)).IgnoreArguments().Return(您刚刚填写的列表))我会变得“真实”数据返回(已从 DataRepository 过滤的数据)。这意味着我可以测试我的代码是否真的能找到一些东西,而不必在我的数据库中插入测试数据(集成测试)。
我将如何着手实现这样的事情?我试过在网上寻找文章或问题,但似乎找不到很多:/
感谢任何帮助。
编辑:我尝试过 SimpleInjector 和 StructureMap,但我无法实现其中之一。
我目前在我的 Entity Framework 上使用一个存储库,所以我的 baseBL 看起来像这样(注意:我的所有其他 BL 继承自这个):
public class BaseBL
{
private IRepository _repository;
public IRepository Repository
{
get
{
if (_repository == null)
_repository = new Repository(new DetacheringenEntities());
return _repository;
}
set { _repository = value; }
}
public IEnumerable<T> GetAll<T>()
{
... --> Generic methods
我的存储库类:
public class Repository : BaseRepository, IRepository
{
#region Base Implementation
private bool _disposed;
public Repository(DetacheringenEntities context)
{
this._context = context;
this._contextReused = true;
}
#endregion
#region IRepository Members
public int Add<T>(T entity)
... --> implementations of generic methods
据我所知,我现在需要能够在我的测试中说明我需要使用我的 DataRepository 而不是 DetacheringenEntities。我不明白如何用数据类切换 Entity Framework ,因为该数据类放不下。
我是否应该让我的 DataRepository 继承我的 IRepository 类并制作我自己的实现?
public class SampleData : IRepository
但是我不能用我的列表做这样的事情:/
public IEnumerable<T> GetAll<T>()
{
return Repository.GetAll<T>();
}
再次感谢您的帮助
编辑:我意识到单元测试不需要数据存储库,所以我只是在集成测试中测试该逻辑。这使得数据存储库变得无用,因为代码可以在没有存储库的情况下进行测试。 不过,我要感谢大家的帮助,谢谢 :)
请您参考如下方法:
使用 Dependency injection framework来处理你的依赖。在您的单元测试中,您可以将实际实现替换为 stub 实现。
例如,在 StructureMap 中,您将在代码中说。 “好吧,现在给我 IDataRepository 的事件实例”,对于您的普通代码,这将指向真实数据库的实现。在您的单元测试中,您可以通过放置 ObjectFactory.Inject(new FakeDataRepository()) 来覆盖它。然后,您的所有代码都会使用伪造的存储库,这使得测试单个工作单元变得非常容易。Í
