How to Mock Entity Framework?

In our previous blog posts, we introduced mocking, and how to mock ASP.NET Identity?

In today’s post we will walk through the steps to mock Entity Framework (EF). Entity Framework is a object-relational mapping framework for ADO.NET. It allows you to work with data as domain-specific objects without having to know the underlying database schema.


In this blog post, we will use a standard ASP.NET MVC project that uses Entity Framework (EF) to work with a database and OWIN Framework for Identity and Authentication. The web application along with the unit tests are available at our public git repo:

For Mocking we will use the popular framework Moq, available as a NuGet package.

How to Mock Asp Entity Framework?

We will use a simple ToDo application to showcase our mocking example. The application allows users to register, login, add/edit their ToDo tasks. The user profile data as well as their ToDo tasks are stored in a database. The application uses EF to interact with the database.

Keeping with our purpose to make our unit tests repeatable, we want to localize our tests and removing any external dependencies. In our scenario, the external dependency is the database abstracted by the EF. So here we would mock EF so that we can interject the calls to the database and there by making all the tests stay local within the process boundaries.

Before we go further there are a couple of core classes of EF that you might want to get familiar with:

  • DbContext is the entry class of EF that is responsible for interacting with data as objects. Think of this as the subset of the database schema (collection of tables, views, stored procedures) that your application interacts with.
  • DbSet is the entity set (table/view/stored procedure) that is used to perform create/read/update/delete (CRUD) operations.

These classes are auto-generated when you import schema objects from your database. This will typically look like:

    public class MyDbContext : DbContext
        public DbSet<MyTable> MyTable { get; set; }
        public DbSet<MyView> MyView { get; set;
        public DbSet<MyStoredProc> MyStoredProc { get; set; } 


To successfully mock EF, we will have to mock DbContext as well as DbSet.

First lets create a mocked DbContext:

    	var m_Context = new Mock<MyDbContext>();

Now we will setup the DbContext to return the mocked DbSet object when its DbSet property is accessed.

To get to that we will first create a list with dummy ToDo objects:

    var todoList = new List<ToDo>();
    var queryable = todoList.AsQueryable();

Now we will set up mocked DbSet to return the above list as IQueryable. This will allow us to run queries against the DbSet.

    var dbSet = new Mock<DbSet<T>>();

    dbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryable.Provider);
    dbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryable.Expression);
    dbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryable.ElementType);
    dbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(() => queryable.GetEnumerator());
    dbSet.Setup(d => d.Add(It.IsAny<T>())).Callback<T>((s) => sourceList.Add(s));
    dbSet.Setup(d => d.Remove(It.IsAny<T>())).Callback<T>(s => sourceList.Remove(s));
    dbSet.Setup(d => d.FindAsync(It.IsAny<object[]>())).Returns<object[]>(ids => Task.FromResult(todoList.Find(t => t.Id == (int)ids[0])));

Now set up the mocked DbContext to return the mocked DbSet.

     m_Context.Setup(c => c.ToDoes).Returns(mockedToDbSet.Object);

With that we have now successfully mocked the EF. Now when you access “ToDoes” properties of mocked DbContext it returns our dummy ToDo’s list. You can now continue adding more mocked DbSet objects as required by your unit test scenarios.

Putting it all together, invoke the controller with mocked DbContext as well as your mocked application user manager that we built in our previous post:

    var todoController = new ToDoController(m_Context, m_userManager);

There you have it. All your unit tests would now be running without any external dependencies.

Let us know if you any questions or suggestions for future topics by commenting below.

This entry was posted in Best Practices, Quality, Unit Testing. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *