ASP.NET Core Interview Question #205
What is mocking and when should it be used?
Testing, Deployment & Hosting Senior Advanced
Quick Interview Answer
Mocking uses a test double that can provide controlled behavior and, when useful, verify interactions with a dependency.
Detailed Explanation
Mocking uses a test double that can provide controlled behavior and, when useful, verify interactions with a dependency.
Mocks are valuable when the interaction itself matters, such as confirming that a notification is sent after a successful operation. They should not be used mechanically for every dependency because excessive mocking can couple tests to implementation details.
Simple fakes or real lightweight objects are often easier to understand when interaction verification is unnecessary.
Code Example
var sender = new Mock<IEmailSender>();
var service = new RegistrationService(sender.Object);
await service.RegisterAsync(user);
sender.Verify(
x => x.SendWelcomeAsync(user.Email),
Times.Once);