DbContext / DbSet Mock for Unit Test in C# with Moq

Brian Peruncelli Collo Gonçalves
2 min readDec 17, 2019

During the start of the development of a project, I came to the challenge of finding a way to be able to test the classes that was using the our DbContext / DbSet without the need to get into the DB.

During the analysis of this, what I wanted to achieve is to have the data stored and retrieve from a List.

The framework I chose to do the mock is called “Moq” ( https://www.nuget.org/packages/moq/ ).

With this, I started by creating a static class to do the DbSet mockup.

With this class, I could start mocking my DbSets from my DbContext in the test SetUp of each individual unit test class, as we can see above:

As we can see in the code above, I can setup my mock for the DbSet with just a couple line of codes:

var myDbMoq = new Mock<IMyDbContext>();myDbMoq.Setup(p => p.Entities).Returns(DbContextMock.GetQueryableMockDbSet<Domain.Entity>(entities));

With this, I have my DbSet ready to be called as a List and be used to retrieve data with Linq or even simulate to add / update a record in the DB.

The entire application code for reference is on a .NET Core 3 Web API template I maintain in github: https://github.com/briangoncalves/NETCore3WebAppTemplate

--

--

Brian Peruncelli Collo Gonçalves

Fullstack developer focused on microsoft technologies (C#, SSRS, SSIS, SqlServer, .NET, .NET Core, EF, etc) and Angular.