Skip to content

Latest commit

 

History

History
43 lines (37 loc) · 986 Bytes

QW0001.md

File metadata and controls

43 lines (37 loc) · 986 Bytes

QW0001: Use a testable Time Provider

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.

Non-compliant

using System;

public class Cookie
{
    public DateTime Expires { get; }
    pulic bool IsValid => Expires >= DateTime.UtcNow;
}

Compliant

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();
        }
    }
}