C# 伪造数据存储库-模拟数据库

C# 伪造数据存储库-模拟数据库,c#,testing,mocking,repository,rhino-mocks,C#,Testing,Mocking,Repository,Rhino Mocks,快速信息:我正在使用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"}

快速信息:我正在使用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; }
    }
}
但我不能用我的清单做这样的事情:/

    public IEnumerable<T> GetAll<T>()
    {
        return Repository.GetAll<T>();
    }
public IEnumerable GetAll()
{
返回Repository.GetAll();
}
再次非常感谢你的帮助

编辑:我意识到单元测试不需要数据存储库,所以我只是在集成测试中测试该逻辑。这使得数据存储库毫无用处,因为代码可以在没有存储库的情况下进行测试。 不过,我还是要感谢大家的帮助,谢谢:)

使用a来处理依赖关系。在您的单元测试中,您可以将真实的实现与存根的实现交换

例如,在StructureMap中,您将在代码中说。“好的,现在给我一个活动实例
IDataRepository
”,对于您的普通代码,这将指向实际数据库的实现。然后,在单元测试中,您可以通过放置
ObjectFactory.Inject(new FakeDataRepository())
来覆盖它。然后,所有代码都会使用伪repo,这使得测试单个工作单元变得非常容易。在您的单元测试中,您可以将真实的实现与存根的实现交换


例如,在StructureMap中,您将在代码中说。“好的,现在给我一个活动实例
IDataRepository
”,对于您的普通代码,这将指向实际数据库的实现。然后,在单元测试中,您可以通过放置
ObjectFactory.Inject(new FakeDataRepository())
来覆盖它。然后,您的所有代码都会使用假回购协议,这使得测试单个工作单元非常容易。嘿,谢谢你的回答。我将尝试实现它(在4.0中)。我会让你知道它是否有效,因为它听起来确实像我需要的:)我在我的问题中添加了一个新的部分,因为我在实现它时遇到了一些问题。嘿,谢谢你的回答。我将尝试实现它(在4.0中)。我会让你知道它是否有效,因为它听起来确实像我需要的:)我在我的问题中添加了一个新的部分,因为我在实现它时遇到了一些问题。看看。好吧,这不仅仅是一个测试,这是我想要设置的,这样我就可以运行多个测试,并且它不会破坏我的数据库。在本例中,我想测试一个搜索函数,其中我的FakeDataRepository中有多个人。当我调用需要测试的methode时,我希望methode使用FakeDataRepository作为源,这样它就可以过滤出正确的人。看一下。这不仅仅是一个测试,而是我想要设置的东西,这样我就可以运行多个测试,而且它不会破坏我的数据库。在本例中,我想测试一个搜索函数,其中我的FakeDataRepository中有多个人。当我调用需要测试的methode时,我希望methode使用FakeDataRepository作为源,这样它就可以过滤出正确的人员。
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
public class SampleData : IRepository
    public IEnumerable<T> GetAll<T>()
    {
        return Repository.GetAll<T>();
    }