csharp / expert
Snippet
Decoupled State Testing
Demonstrates manual dependency injection for testability. By abstracting system primitives like time into interfaces, code becomes deterministically testable without relying on external system state.
snippet.cs
csharp
1
2
3
4
5
6
7
8
public interface IDateTimeProvider { DateTime Now { get; } }public class Processor(IDateTimeProvider timer){public bool IsExpired(DateTime expiry) => timer.Now > expiry;}// In Test: var mock = new MockTimer { Now = fixedDate };
Breakdown
1
public interface IDateTimeProvider
Defines an abstraction for a non-deterministic resource (System Time).
2
public class Processor(IDateTimeProvider timer)
Uses a primary constructor to inject the dependency for isolation.