csharp / intermediate
Snippet
Decoupling Logic for Verifiable Unit Tests
To make code testable, dependencies (like a message service) should be passed via interfaces rather than instantiated directly. This pattern, combined with C# 12 primary constructors, allows you to easily inject 'mock' objects during testing to verify logic in isolation.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface IMessageService { void Send(string msg); }public class OrderProcessor(IMessageService service){public void CompleteOrder(int id){// Business logic here...service.Send($"Order {id} completed.");}}// In test: Create a mock implementation of IMessageService// to verify Send was called without sending real emails.
Breakdown
1
public class OrderProcessor(IMessageService service)
Uses a primary constructor to declare and receive the dependency.
2
service.Send($"Order {id} completed.");
The logic depends on the abstraction (interface), making it easy to swap for a test double.