Search Sreeni's Insights

Filter by content type
crafting February 6, 2018 4 min read

How to unit test Entity Framework Core?

Unit test code that uses Entity Framework Core with test doubles for DbContext and DbSet, so the tests stay fast and focused on the system under test.

Share:

How to unit test Entity Framework Core?

Introduction

A unit test focuses only on the system under test (SUT) and it does not test the SUT’s collaborators. Then you might ask how to manage the dependencies. It is a very good question, and the answer is not easy. Fortunately, we have test double techniques to manage the SUT’s dependencies. Test doubles are out of the scope of this post, and you can refer to this link to get more information on test doubles.

In this article, we are going to see how to write unit tests against Entity Framework Core. As you are aware, EF is one of the most popular ORM frameworks on the .NET platform. EF Core comes with a built-in option to enable an in-memory store, and it acts as a fake test double. Alternatively, you can use mock frameworks to create any flavour of test double.

We are going to see both options in this article, and for both options we are going to take a common example. Assume you have an e-commerce site in ASP.NET Core and it has product management along with other features. So, you have a ProductsController, a ProductRepository and an EF DbContext, and the code implementation looks like below,

Products Controller:

namespace Wingtip.Toys.ECommerce.Controllers
{
    [Route("products")]
    public class ProductsController : Controller
    {
        private readonly IProductRepository _productRepository;

        public ProductsController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }

        [Route("list")]
        public IActionResult List()
        {
            var products = _productRepository.GetAll();
            return View(products);
        }

        [Route("{category}")]
        public IActionResult Index(string category)
        {
            var products = _productRepository.GetByCategoryName(category);
            return View(products);
        }

        [Route("details/{id}")]
        public IActionResult Details(int id)
        {
            var product = _productRepository.GetById(id);
            return View(product);
        }
    }
}

Repository Contracts:

namespace Wingtip.Toys.Data.Contract
{
    public interface IRepository<T>
    {
        T GetById(int id);
        T Add(T t);
        bool Update(T t);
        bool Delete(int id);
        IEnumerable<T> GetAll();
    }
}

namespace Wingtip.Toys.Data.Contract
{
    public interface IProductRepository : IRepository<Product>
    {
        IEnumerable<Product> GetByCategoryName(string category);
    }
}

Product Repository:

namespace WingTip.Toys.Data.Repository
{
    public class ProductRepository : IProductRepository
    {
        private readonly WingtipToysDbContext _dbContext;

        public ProductRepository()
        {
            _dbContext = new WingtipToysDbContext();
        }

        public ProductRepository(WingtipToysDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public Product GetById(int id)
        {
            return _dbContext.Products.Include("Category").First(p => p.ProductID == id);
        }

        public Product Add(Product product)
        {
            var result = _dbContext.Products.Add(product);
            _dbContext.SaveChanges();
            return result.Entity;
        }

        public bool Update(Product product)
        {
            var result = _dbContext.Products.Update(product);
            _dbContext.SaveChanges();
            return result.State == EntityState.Modified;
        }

        public bool Delete(int id)
        {
            var product = GetById(id);
            if (product == null)
                throw new InvalidOperationException("Product Not Exists!");

            var result = _dbContext.Products.Remove(product);
            _dbContext.SaveChanges();
            return result.State == EntityState.Deleted;
        }

        public IEnumerable<Product> GetAll()
        {
            return _dbContext.Products.Include("Category").ToList();
        }

        public IEnumerable<Product> GetByCategoryName(string category)
        {
            return _dbContext.Products.Include("Category").Where(p => p.Category.CategoryName == category);
        }
    }
}

Db Context:

public class WingtipToysDbContext : DbContext
{
    public WingtipToysDbContext()
    {
    }

    public WingtipToysDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
            optionsBuilder.UseSqlServer("<connection string goes here>");
    }

    public virtual DbSet<Category> Categories { get; set; }

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

In Memory Database

The in-memory option creates and connects to an in-memory fake database, which helps us to write unit tests without violating the FIRST properties of a unit test. This feature is available in the Microsoft.EntityFrameworkCore.InMemory NuGet package, so you need to add this package to your test project if you don’t have it already. The second prerequisite is that your DbContext class should accept DbContextOptions. The third is optional: you should check whether the options are already configured before you set the connection string in the OnConfiguring method. Use the following snippet to enable the in-memory option once you have added the required package to your project.

var options = new DbContextOptionsBuilder<WingtipToysDbContext>()
                .UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options;

var dbContext = new WingtipToysDbContext(options);

Here, we need to use the UseInMemoryDatabase extension method of DbContextOptionsBuilder. This method takes the database name as an argument, and you can provide whatever you want. In this example, I used a Guid to set a unique name for the database. Assume we have the following test cases that the product repository needs to satisfy, and let’s write the required unit tests for these test cases with the EF in-memory database,

  1. It should add a product successfully into the data store
  2. It should update a product successfully in the data store
  3. It should remove a product successfully from the data store
[TestClass]
public class ProductRepositoryTest
{
    private WingtipToysDbContext CreateDbContext()
    {
        var options = new DbContextOptionsBuilder<WingtipToysDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options;

        var dbContext = new WingtipToysDbContext(options);
        return dbContext;
    }

    [TestMethod]
    public void It_should_add_a_product_successfully_into_data_store()
    {
        //Arrange
        var dbContext = CreateDbContext();
        var sut = new ProductRepository(dbContext);
        var product = new Product { Description = "Model S - Tesla", ProductName = "Tesla Car - Model S", UnitPrice = 10000 };

        //Act
        var result = sut.Add(product);

        //Assert
        Assert.IsTrue(result.ProductID > 0);

        //Clean up
        dbContext.Dispose();
    }

    [TestMethod]
    public void It_should_update_a_product_successfully_into_data_store()
    {
        //Arrange
        var expected = 20000;
        var dbContext = CreateDbContext();
        var sut = new ProductRepository(dbContext);
        var product = new Product { Description = "Model S - Tesla", ProductName = "Tesla Car - Model S", UnitPrice = 10000 };

        //Act
        var result = sut.Add(product);
        result.UnitPrice = expected;
        sut.Update(result);
        result = dbContext.Products.First(p => p.ProductID == result.ProductID);

        //Assert
        Assert.AreEqual(expected, result.UnitPrice);

        //Clean up
        dbContext.Dispose();
    }

    [TestMethod]
    public void It_should_remove_a_product_successfully_from_the_data_store()
    {
        //Arrange
        var dbContext = CreateDbContext();
        var sut = new ProductRepository(dbContext);
        var product = new Product { Description = "Model S - Tesla", ProductName = "Tesla Car - Model S", UnitPrice = 10000 };

        //Act
        var result = sut.Add(product);
        sut.Delete(result.ProductID);
        var isExists = dbContext.Products.Any(p => p.ProductID == result.ProductID);

        //Assert
        Assert.IsFalse(isExists);

        //Clean up
        dbContext.Dispose();
    }
}

In this example, the CreateDbContext method enables the in-memory database with a Guid name, then creates and returns a DbContext object with the in-memory option. Whenever you call this method, it creates a new DbContext object with a new in-memory database instead of the real database. Once you have created the DbContext object, you can do whatever you want with it.

Using Mock Frameworks

Alternatively, you can use mock frameworks to create a test double and write the unit tests without using the real database. In this example, I am using Moq, which is one of the popular mock frameworks for the .NET platform. Before you start writing the unit tests, you should ensure all of the DbContext’s DbSet properties are marked as virtual; only then can the Moq framework create a fake object and override these properties. You must do the following steps with your mock framework,

  1. Create a generic collection for each DbSet property
  2. Configure your fake DbSet in your mock framework
  3. Set up the following DbSet properties and methods to forward to the generic collection,
    • Provider
    • Expression
    • ElementType
    • GetEnumerator()

Let’s continue to write some more unit tests for the following test cases for the product repository,

  1. It should throw an invalid operation exception when the user tries to delete a non-existing product
  2. It should list all available products from the data store
  3. It should return a product for the given product id
  4. It should return a list of products for the given product category name
[TestClass]
public class ProductRepositoryTest
{
    private DbSet<T> CreateDbSet<T>(IQueryable<T> collection) where T : class
    {
        var stubDbSet = new Mock<DbSet<T>>();
        stubDbSet.As<IQueryable<T>>().Setup(m => m.Provider).Returns(collection.Provider);
        stubDbSet.As<IQueryable<T>>().Setup(m => m.Expression).Returns(collection.Expression);
        stubDbSet.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(collection.ElementType);
        stubDbSet.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(collection.GetEnumerator());
        return stubDbSet.Object;
    }

    [TestMethod]
    [ExpectedException(typeof(InvalidOperationException))]
    public void It_should_throw_invalid_operation_exception_when_try_to_delete_a_non_existing_product()
    {
        //Arrange
        var collection = new List<Product>
        {
            new Product {ProductName = "Tesla Model 3", ProductID = 1},
            new Product {ProductName = "Tesla Model S", ProductID = 2},
            new Product {ProductName = "Tesla Model X", ProductID = 3}
        };

        var productDbSet = CreateDbSet(collection.AsQueryable());

        var stubContext = new Mock<WingtipToysDbContext>();
        stubContext.Setup(o => o.Products).Returns(productDbSet);
        var sut = new ProductRepository(stubContext.Object);

        //Act
        var actual = sut.Delete(4);
    }

    [TestMethod]
    public void It_should_list_all_available_products_from_the_data_store()
    {
        //Arrange
        var expected = new List<Product>
        {
            new Product {ProductName = "Tesla Model 3"},
            new Product {ProductName = "Tesla Model S"},
            new Product {ProductName = "Tesla Model X"}
        };

        var productDbSet = CreateDbSet(expected.AsQueryable());

        var stubContext = new Mock<WingtipToysDbContext>();
        stubContext.Setup(o => o.Products).Returns(productDbSet);
        var sut = new ProductRepository(stubContext.Object);

        //Act
        var actual = (List<Product>)sut.GetAll();

        //Assert
        CollectionAssert.AreEquivalent(expected, actual);
    }

    [TestMethod]
    public void It_should_return_a_product_for_given_product_id()
    {
        //Arrange
        var expected = "Tesla Model S";
        var collection = new List<Product>
        {
            new Product {ProductName = "Tesla Model 3", ProductID = 1},
            new Product {ProductName = "Tesla Model S", ProductID = 2},
            new Product {ProductName = "Tesla Model X", ProductID = 3}
        };

        var productDbSet = CreateDbSet(collection.AsQueryable());

        var stubContext = new Mock<WingtipToysDbContext>();
        stubContext.Setup(o => o.Products).Returns(productDbSet);
        var sut = new ProductRepository(stubContext.Object);

        //Act
        var actual = sut.GetById(2);

        //Assert
        Assert.AreEqual(expected, actual.ProductName);
    }

    [TestMethod]
    public void It_should_return_list_of_product_for_given_product_category_name()
    {
        //Arrange
        var products = new List<Product>
        {
            new Product {ProductName = "Tesla Model 3", ProductID = 1, Category = new Category {CategoryName = "Car", CategoryID = 1}},
            new Product {ProductName = "Tesla Model S", ProductID = 2, Category = new Category {CategoryName = "Car", CategoryID = 1}},
            new Product {ProductName = "Tesla Model X", ProductID = 3, Category = new Category {CategoryName = "Car", CategoryID = 1}}
        };

        var productDbSet = CreateDbSet(products.AsQueryable());
        var stubContext = new Mock<WingtipToysDbContext>();
        stubContext.Setup(o => o.Products).Returns(productDbSet);
        var sut = new ProductRepository(stubContext.Object);

        //Act
        var actual = sut.GetByCategoryName("Car").ToList();

        //Assert
        CollectionAssert.AreEquivalent(products, actual);
    }
}

In the above example, I have used the CreateDbSet method, which creates a stub for DbSet and sets up the call forwarding of some of the properties and methods to the given collection. In the same way, you can create other test doubles. I hope you find something useful in this article; please share your comments.

Related Posts