Menu

C# Unit test a Repository class using a Seeded InMemoryDatabase

If you wanted to unit test a Repository that uses a DbContext with seeded data, you can use the InMemoryDatabase.

You will need to add NuGet “Microsoft.EntityFrameworkCore.InMemory”

I will use a base class to initialise the seeded DbContext, looks somethign like below

    public class BaseRepositoryTests
    {
        protected readonly MyDbContext context;
        public BaseRepositoryTests()
        {
            var dbContextOptions = new DbContextOptionsBuilder<MyDbContext>().UseInMemoryDatabase(Guid.NewGuid().ToString());
            context = new MainContext(dbContextOptions.Options);
            context.Category.AddRange(.....);
            context.SaveChanges();
        }
    }

Then you can use the “BaseRepositoryTests” on your test class like below

public class CategoryRepositoryTests : BaseRepositoryTests
{
        private ICategoryRepository _repository;

        public CategoryRepositoryTests()
        {
            _repository= new CategoryRepository(context);
        }

        [Fact]
        public async Task ShouldReturnNull()
        {
            var sc = await _repository.GetByIdAsync(-1);

            Assert.Null(sc);
        }

}

That is it.

Leave a comment