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
.
The Entity Framework DbContext class is based on the Unit of Work and Repository patterns and can be used directly from your code, such as from an ASP.NET Core MVC controller.
Mocking is a way to encapsulate your unit tests. If you want to test a service method you are not interested if the repository is working. For this you will write repository tests. Therefore you mock the repository call and tell which result should be returned to test your method in all possible situation.
Mocking is a process that allows you to create a mock object that can be used to simulate the behavior of a real object. You can use the mock object to verify that the real object was called with the expected parameters, and to verify that the real object was not called with unexpected parameters.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With