vendredi 10 juillet 2015

Mocking database in EF6 db first

I'm having trouble figuring out how to mock my database for unit testing my web api controllers. All the resources I've found work for code first EF but not db first where my context is auto-generated.

Put simply I want to be able to call my controller's CRUD operations against a fake database I create on the fly and am looking for the most straight forward method of doing this.

I'm trying to use http://ift.tt/1Hi2RaA to put it together but cannot manage...

My context is defined as:

public partial class MyEntities : DbContext
{
    public MyEntities()
        : base("name=MyEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Company> Companies { get; set; }

Now I understand that I need to create an IContext which allows the mocking of MyEntities, but I cannot figure out how to organize this.

I've tried adding the below classes but can't figure out how to organize it past this.

public interface IContext
{
    IObjectSet<Company> Companies { get; }

    void SaveChanges();
}

public class EFContext: IContext
{
    private readonly MyEntities _data;

    public EFContext()
    {
        _data = new MyEntities();
    }

    public IObjectSet<Company> Companies
    {
        get 
        {
            return _data.CreateObjectSet<Company>();
        }
    }

    public void SaveChanges()
    {
        _data.SaveChanges();
    }
}

  1. How can I mock my EF database first context to use a test database?

Aucun commentaire:

Enregistrer un commentaire