【发布时间】:2011-10-13 11:48:52
【问题描述】:
快速信息:我正在使用 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; }
}
}
所以这是一个模仿数据库中数据的类。现在我想在我的单元测试中使用这些数据。换句话说,我不想将数据从数据库中取出,而是将它们从数据存储库中取出。
我认为我可以通过存根存储库并使其使用 DataRepository 来实现这一点:
UC1003_ConsultantsBeherenBL consultantsBeherenBL = new UC1003_ConsultantsBeherenBL();
consultantsBeherenBL = MockRepository.GeneratePartialMock<UC1003_ConsultantsBeherenBL>();
consultantsBeherenBL.Repository = MockRepository.GenerateMock<IRepository>();
这将导致我的代码改为自动在 DataRepository 中查找数据。因此,与其对方法进行存根并直接插入一个列表(例如 d => d.Find(Arg.Is.Anything)).IgnoreArguments().Return(a list which you just fill up))我会得到“真实的”返回数据(已从 DataRepository 过滤的数据)。这意味着我可以测试我的代码是否真的能找到某些东西,而无需在我的数据库中插入测试数据(集成测试)。
我将如何实施这样的事情?我试过在网上寻找文章或问题,但似乎找不到很多:/
感谢任何帮助。
编辑:我尝试过 SimpleInjector 和 StructureMap,但我无法实现其中之一。
我目前在我的实体框架上使用一个存储库,所以我的 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。我不明白如何用数据类切换我的实体框架,因为该数据类不适合在那里。
我应该让我的 DataRepository 继承我的 IRepository 类并自己实现吗?
public class SampleData : IRepository
但我不能用我的列表做这样的事情:/
public IEnumerable<T> GetAll<T>()
{
return Repository.GetAll<T>();
}
再次感谢您的帮助
编辑:我意识到单元测试不需要数据存储库,所以我只是在集成测试中测试该逻辑。这使得数据存储库毫无用处,因为可以在没有存储库的情况下测试代码。 不过还是要感谢大家的帮助,谢谢:)
【问题讨论】:
-
看看this article。
-
嗯,这不只是为了一个测试,它是我想要设置的,所以我可以运行多个测试,它不会破坏我的数据库。在这种情况下,我想测试一个搜索功能,我的 FakeDataRepository 中有多个人。当我调用需要测试的methode时,我希望methode使用FakeDataRepository作为源,这样可以过滤出正确的Persons。
标签: c# testing mocking repository rhino-mocks