Strategies for working with DateTime.Now in unit tests

I have a business logic that doesn’t perform certain functions on Saturday or Sunday. I want my unit tests to verify that these functions are running, but the tests will not be executed on Saturday / Sunday.

I believe that the easiest route is to let the unit tests pass a friendly message that the test results are invalid if they are run on Saturday / Sunday.

C # / NUnit ...

Assert.That(
  DateTime.Now.DayOfWeek != DayOfWeek.Sunday && DateTime.Now.DayOfWeek !=      
  DayOfWeek.Saturday, "This test cannot be run on Saturday or Sunday");

Is it possible / advisable to try to make fun of the date? Are there other strategies to handle this scenario?

+3
source share
2 answers

Is it possible / advisable to try and make fun of the date?

, , , unit test . , () :

public bool Foo()
{
    return (DateTime.Now.DayOfWeek == DayOfWeek.Sunday);
}

, , ( Now). , , , .

( DI):

private readonly Func<DateTime> _nowProvider;
public SomeClass(Func<DateTime> nowProvider)
{
    _nowProvider = nowProvider;
}

public bool Foo()
{
    return (_nowProvider().DayOfWeek == DayOfWeek.Sunday);
}

unit test. SomeClass . , , SomeClass :

var s = new SomeClass(() => DateTime.Now);
s.Foo();

unit test , :

var subjectUnderTest = new SomeClass(() => new DateTime(2011, 1, 3));
var actual = subjectUnderTest.Foo();
// assertions, ...
+8

, , RTM unit.

:

public interface ISystemClock
{
    DateTime Now { get; }
}

, , , , ISystemClock. ISystemClock, :

public class FakeSystemClock : ISystemClock
{
    // Note the setter.
    public DateTime Now { get; set; }
}

:

[TestMethod]
[ExpectedException(typeof(InvalidOperationException),
    "Service should throw an exception when called on saturday.")]
public void DoSomething_WhenCalledOnSaturday_ThrowsException()
{
    // Arrange
    var saturday = new DateTime(2011, 1, 1);
    Assert.AreEqual(saturday.DayOfWeek, DayOfWeek.Saturday,
        "Test setup fail");
    var clock = new FakeSystemClock() { Now = saturday };
    var service = new Service(clock);

    // Act
    service.DoSomething();
}

ISystemClock, . ISystemClock, :

public class RealSystemClock : ISystemClock
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

DI, RealSystemClock, ISystemClock.

. Func<DateTime>, , . , DI , Func<DateTime>, , " ".

, .

+1

Source: https://habr.com/ru/post/1783409/


All Articles