csharp / expert
Snippet
Dependency Isolation via Method Injection
Expert-level unit testing often relies on 'Pure Functions' or dependency injection. Passing an interface directly to a method (Method Injection) allows for perfect isolation during testing without the overhead of heavy mocking frameworks.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public interface ISystemClock { DateTime Now { get; } }public class DiscountService {public decimal Calculate(decimal price, ISystemClock clock) {// Injecting the interface directly into the method for maximum testabilityreturn clock.Now.DayOfWeek == DayOfWeek.Friday ? price * 0.9m : price;}}// Testing: service.Calculate(100, new MockClock(DayOfWeek.Friday));
Breakdown
1
ISystemClock clock
Abstracts the volatile dependency (system time) to make the logic deterministic.
2
price * 0.9m
Uses the decimal literal suffix 'm' to ensure high-precision financial calculations.