0 day streak
csharp / intermediate
Snippet

Designing Mockable Components for Tests

By using interfaces for external dependencies, you make your code testable. During unit testing, you can pass a 'mock' implementation of the interface instead of the real service to verify behavior without side effects.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
public interface IEmailService
{
void Send(string message);
}
public class NotificationManager
{
private readonly IEmailService _service;
public NotificationManager(IEmailService service) => _service = service;
public void Notify(string msg) => _service.Send(msg);
}
Breakdown
1
private readonly IEmailService _service;
Stores a reference to the abstraction rather than a concrete class.
2
public NotificationManager(IEmailService service)
Constructor injection allows passing different implementations (real or test) at runtime.