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 th开发者_Python百科is:
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
.
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());
精彩评论