[英]test Entity Framework Models
I'm going to test my EF Models. 我要测试我的EF模型。 In order to do this I've create IDbContext class. 为了做到这一点,我创建了IDbContext类。 But I don't know how to rewrite my Save and Delete methods, because I don't know how to write db.Partner.AddObject(obj); 但我不知道如何重写我的Save和Delete方法,因为我不知道如何编写db.Partner.AddObject(obj); How to rewrite these methods? 如何重写这些方法?
public interface IDbContext
{
int SaveChanges();
DbSet<Partner> Partner { get; set; }
}
public class PartnerRepository : IPartnerRepository
{
readonly IDbContext _context;
public PartnerRepository()
{
_context = (IDbContext)new VostokPortalEntities();
}
public PartnerRepository(IDbContext context)
{
_context = context;
}
public void Save(Partner obj)
{
using (var db = new VostokPortalEntities())
{
if (obj.PartnerID == 0)
{
db.Partner.AddObject(obj);
}
else
{
db.Partner.Attach(obj);
db.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Modified);
}
db.SaveChanges();
}
}
public void Delete(Partner obj)
{
using (var db = new VostokPortalEntities())
{
db.Partner.Attach(obj);
db.ObjectStateManager.ChangeObjectState(obj, System.Data.EntityState.Deleted);
db.SaveChanges();
}
}
public List<Partner> GetAll()
{
using (var db = new VostokPortalEntities())
{
return db.Partner.OrderByDescending(i => i.PartnerID).ToList();
}
}
}
Is this proper way to test EF Models? 这是测试EF模型的正确方法吗?
Unit-testing of repositories takes a lot of time and does not give you many benefits. 存储库的单元测试需要花费大量时间,并没有给您带来很多好处。 Why? 为什么? Because repository don't have complex business logic. 因为存储库没有复杂的业务逻辑。 Usually there is pretty simple calls to underlying data-access API (ie ORM). 通常,对底层数据访问API(即ORM)进行非常简单的调用。 I think it's match better to spend time on writing full-stack acceptance tests, which also will show if your repository do its job. 我认为花时间编写全栈验收测试更好,这也将显示你的存储库是否能完成它的工作。
BTW there is interesting rule Don't Mock what you don't own : BTW有一个有趣的规则不要嘲笑你不拥有的东西 :
By testing interactions with a mocked version of type we don't own, we really are not using our test to check for the correct behavior, nor to drive out a collaborator's design. 通过测试与我们不拥有的类型的模拟版本的交互,我们确实没有使用我们的测试来检查正确的行为,也没有推出协作者的设计。 All our test is doing is reiterating our guess as to how the other type works. 我们所做的所有测试都重申了我们对其他类型如何工作的猜测。 Sure, it's better than no test, but not necessarily by much. 当然,它比没有测试好,但不一定非常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.