用于单元测试的 C# 通用存储库
我有以下用于单元测试的假存储库。我将如何在此存储库中实现 Attach(T实体) 方法?
(在我的真实存储库中,Attach(T实体)方法用于将对象附加到我的实体框架4数据上下文)。
public class FakeRepository<T> : IRepository<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;
}
}
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> : IRepository<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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答这个问题,您必须问自己““
Attach
”的目的是什么?”您可能知道重点是告诉存储库“该对象已保存在数据库中,但您没有目前正在追踪它;我已经对其进行了更新,并且希望您在我告诉您提交更改时提交这些更新。”因此,要测试
Attach
是否正常工作,您应该维护附加对象的集合并添加当将参数传递给Attach
时,将实体添加到此集合中。因此,最简单的实现是,
但您可以考虑更细粒度的方法,请注意,您需要公开一个允许您断言的方法。实体已成功附加(在 EF4 中,您可以使用
ObjectStateManager.TryGetObjectStateEntry
)。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 toAttach
.So, the simplest implementation would be
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