David Horák
David Horák

Reputation: 5565

Mocking repository with Entity Framework

I'm using mog for mocking a repository with LINQ to SQL like this:

public static IProductsRepository MockProductsRepository(params Product[] prods){
    // Generate an implementer of IProductsRepository at runtime using Moq
    var mockProductsRepos = new Mock<IProductsRepository>();
    mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());
    return mockProductsRepos.Object;
}

public interface IProductsRepository{
    IQueryable<Product> Products { get; }
    void SaveProduct(Product product);
    void DeleteProduct(Product product);
}

How can I change this function for the Entity framework if I am using it like this:

public interface IProductsRepository : IEntities{
    EntityState GetEntryState(object entry);
    void SetEntryState(object entry, EntityState state);
    void Commit();
}

public interface IEntities{
    DbSet<Product> Products { get; set; }
}

Now I am using DbSet.

Upvotes: 6

Views: 1916

Answers (1)

Sergi Papaseit
Sergi Papaseit

Reputation: 16174

Well, Since IProductsRepository implements IEntities you should have a

public DbSet<Product> Products { get; set; }

property in there, but what I would do is add a Fetch method to IProductRepository like

public interface IProductsRepository : IEntities
{
    EntityState GetEntryState(object entry);
    void SetEntryState(object entry, EntityState state);
    void Commit();

    // New method
    IQueryable<Product> FetchAll();
}

Then, in your MockProductsRepository change the setup line as follows:

mockProductsRepos.Setup(x => x.FetchAll()).Returns(prods.AsQueryable());

Upvotes: 2

Related Questions