Skip to content

FakeDbContext

Simon Hughes edited this page Oct 12, 2022 · 5 revisions

FakeDbContext inherits from the base class of your DbContext and can be used in unit tests instead of your real DbContext.

If you create a repository class with simple Count() and Find() functions you want to test:

public class CustomersRepository : ICustomersRepository
{
    private readonly IMyDbContext _context;

    public CustomersRepository(IMyDbContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public int Count()
    {
        return _context.Customers.Count();
    }

    public Customer Find(string id)
    {
        return _context.Customers.Find(id);
    }
}

You could test your repository with:

[TestFixture]
public class CustomersRepositoryTests
{
    private ICustomersRepository _customersRepository;
    private IMyDbContext _context;

    [SetUp]
    public void Setup()
    {
        // Arrange
        _context = new FakeMyDbContext();

        var list = new List<Customer>
        {
            new Customer
            {
                CustomerId = "1",
                CompanyName = "abc"
            },
            new Customer
            {
                CustomerId = "2",
                CompanyName = "def"
            }
        };

        _context.Customers.AddRange(list);
        _customersRepository = new CustomersRepository(_context);
    }

    [Test]
    public void GetCount()
    {
        // Act
        int count = _customersRepository.Count();

        // Assert
        Assert.AreEqual(2, count);
    }

    [Test]
    public void Find()
    {
        // Act
        var abc = _customersRepository.Find("1");
        var def = _customersRepository.Find("2");
        var ghi = _customersRepository.Find("3");

        // Assert
        Assert.IsNotNull(abc);
        Assert.IsNotNull(def);
        Assert.IsNull(ghi);

        Assert.AreEqual("abc", abc.CompanyName);
        Assert.AreEqual("def", def.CompanyName);
    }
}

EF Core In-Memory Database Provider

This is an alternative to the above FakeDbContext.

Install-Package Microsoft.EntityFrameworkCore.InMemory

This database provider allows Entity Framework Core to be used with an in-memory database. This can be useful for testing, although the SQLite provider in in-memory mode may be a more appropriate test replacement for relational databases. Further info: EF Core In-Memory Database Provider

For full instructions and examples on how to the in-memory provider, please read Testing with InMemory

Clone this wiki locally