For testability, the behavior of time providers should
be adjustable under test. DateTime.Now
, DateTime.UtcNow
,
DateTime.Today
, DateTimeOffset.Now
, and DateTimeOffset.UtcNow
lack this possibility.
Note that Sonar has rule S6354. If you prefer, you could use that rule instead.
using System;
public class Cookie
{
public DateTime Expires { get; }
pulic bool IsValid => Expires >= DateTime.UtcNow;
}
using Qowaiv;
public class Cookie
{
public DateTime Expires { get; }
public bool IsValid => Expires >= Clock.UtcNow();
}
public class CookieTest
{
[Test]
public void Invalid_when_expired()
{
using(Clock.SetTimeForCurrentThread(() => new DateTime(2017, 06, 11))
{
new Cookie(expires: new DateTime(2017, 06, 12))
.IsValid.Should().BeFalse();
}
}
}