Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 689
David Horák Avatar asked Mar 04 '11 14:03

David Horák


People also ask

Does Entity Framework use Repository pattern?

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.

What is mock repository?

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.

What is C# mocking?

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.


1 Answers

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());
like image 134
Sergi Papaseit Avatar answered Sep 19 '22 17:09

Sergi Papaseit