开发者

C# generic repository used for unit testing

I have the following fake repository that I use for unit testing. How would I implement the Attach(T entity) method in this repository?

(In my real repository, the Attach(T entity) method is used to attach an object to my Entity Framework 4 data context).

public class FakeRepository<T> : IRep开发者_如何学Pythonository<T> where T : class, new()
{
    private static List<T> entities = new List<T>();

    public IQueryable<T> Entities
    {
        get { return entities.AsQueryable(); }
    }

    public T New()
    {
        return new T();
    }

    public void Create(T entity)
    {
        entities.Add(entity);
    }

    public void Delete(T entity)
    {
        entities.Remove(entity);
    }

    public void Attach(T entity)
    {
        //How to implement Attach???
    }

    public void Save()
    {
        //Do nothing
    }

    public void Dispose()
    {
        return;
    }
}


To answer this, you have to ask yourself "what is the purpose of "Attach?" You probably know that the point is to tell the repository "this object is persisted in the database but you aren't currently tracking it; I have made updates to it and I want you to commit them when I tell you to submit your changes."

Thus, to test that Attach is working properly, you should maintain a collection of attached objects and add an entity to this collection when it is passed a parameter to Attach.

So, the simplest implementation would be

entities.Add(entity);

but you could consider something more fine-grained. Note that you need to expose a method that lets you assert that the entity was successfully attached (in EF4 you can use ObjectStateManager.TryGetObjectStateEntry).


get rid of the static word on the entities member. Now just do

enitities.Add(entity)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜