Does Anyone Know What Time It Is?
If you’ve ever written a unit test that failed only on Tuesdays , only after midnight , or only on CI but never locally , then congratulations — you’ve been personally victimized by DateTime.Now . Time is one of those sneaky dependencies we rarely think about… until it breaks our tests. Thankfully, modern C# finally gives us a first-class way to deal with time in a testable, civilized way: ๐ TimeProvider Let’s talk about why it exists, why it matters, and how it makes your unit tests calmer, cleaner, and way less haunted. ๐งจ The Classic Problem: Time Is a Liar Here’s a pattern we’ve all written: public bool IsExpired ( DateTime expiresOn ) { return DateTime.Now > expiresOn; } Seems harmless, right? Now try to unit test it. What time is it right now ? What happens if the test runs at midnight? What about daylight saving time? What if the test is slow? What if it runs in a different time zone? You don’t control time — time controls you . ๐ง Enter: TimePr...