1

I'm going to test my EF Models. In order to do this I've create IDbContext class. 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); 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?

1 Answer 1

4

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 (i.e. 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:

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.