Tutorials ADO.NET Core Tutorial
Mocking Database Calls — Complete Guide
Mocking Database Calls — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of ADO.NET Core Tutorial on Toolliyo Academy.
On this page
ADO.NET Core Tutorial · Lesson 73 of 100
Mocking Database Calls
Foundations ✓ → SQL & safety ✓ → Production → Projects
Production · 3 — ASP.NET & enterprise · ~10 min · Module 8: Testing and Debugging
What is this?
Mock IOrderRepository with Moq/NSubstitute for unit tests; don’t mock SqlConnection internals.
Why should you care?
ShopNest controller tests need mocks, not SQL.
See it live — copy this example
Use a .NET console or API project with SQL Server LocalDB. Run dotnet run after pasting.
var mock = new Mock<IOrderRepository>();
mock.Setup(r => r.GetPendingAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(new[] { new OrderDto(1, 5, "Pending") });
What happened?
- Mock ports, not SqlCommand.
- Integration tests cover SQL.
Practice next
- Moq GetPendingAsync.
- Assert controller OK.
- Verify call once.
- Throw SqlException from mock mapped path.
- Null empty list.
Remember
Mock repository ports. Not SqlConnection. Verify interactions.
ShopNest controller mocks
API tests mock IOrderRepository.
Outcome: No SQL needed for HTTP unit tests.
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!