Tutorials Entity Framework Core Tutorial
Mocking Repositories in EF Core Tests
Mocking Repositories in EF Core Tests: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 85 of 100
Mocking Repositories in EF Core Tests
Beginner ✓ → Intermediate ✓ → Advanced ✓ → Professional
Professional · 4 — Real projects · ~10 min · Module 9: Testing & Debugging
What is this?
Mocking repositories means substituting IProductRepository or IUnitOfWork with Moq or NSubstitute fakes so Application code tests without DbContext.
Why should you care?
ShopNest NotificationService tests verify email sent after order — mock IOrderRepository to return order without EF.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
var orderRepo = new Mock<IOrderRepository>();
orderRepo.Setup(r => r.GetByIdAsync(42, It.IsAny<CancellationToken>()))
.ReturnsAsync(new Order { Id = 42, CustomerId = 7 });
var uow = new Mock<IUnitOfWork>();
uow.Setup(u => u.Orders).Returns(orderRepo.Object);
var svc = new OrderNotificationService(uow.Object, emailSender);
await svc.SendConfirmationAsync(42, CancellationToken.None);
emailSender.Verify(e => e.SendAsync(It.IsAny<string>(), It.IsAny<string>()), Times.Once);
What happened?
- Moq configures GetByIdAsync return.
- Service under test never touches EF.
- Verify email sender called once — behavior assertion.
Practice next
- Mock interfaces Application already uses — not DbSet directly.
- Setup ReturnsAsync with realistic domain objects.
- Verify interactions when testing side effects.
- Use NSubstitute Returns syntax for same test.
- Mock IUnitOfWork.SaveChangesAsync to verify commit called.
Remember
Mock repository interfaces not DbContext. Moq/NSubstitute configure async returns. Pair with few integration tests for EF paths.
ShopNest email unit test
OrderNotificationService tested with mocked IOrderRepository and IEmailSender.
Outcome: Email template logic covered without SMTP or SQL in unit test job.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!