Search code examples
c#unit-testingdatetimensubstitute

NSubstitute DateTime.Now() How can I get the DateTime.Now() to return an ever increasing date and time?


I have several unit tests in which we use NSubstitute for the DateTime. In some cases I want to increment the DateTime.Now() by some set amount so that each time it is called, the date and time are incremented a little. Currently I have:

  private int minutesToAdd = 1;
  private DateTime dateToUse = new DateTime(2018, 1, 1, 0, 0, 0);
  DateTime = Substitute.For<IDateTime>();
  DateTime.Now().Returns(dateToUse.AddMinutes(minutesToAdd)).AndDoes(x => minutesToAdd++) ;

This returns 1/1/2/2018 00:01 every time the function is called.
I thought the "AndDoes" would increment the minutesToAdd each time and would increase the time by one minute.
Can I get the DateTime substitute to increment by one minute each time it is called?


Solution

  • There should be an overload of Returns() that accepts a Func<,>, try it:

    var DateTime = Substitute.For<IDateTime>();
    
    DateTime.Now().Returns(x =>
    {
        var dt = dateToUse.AddMinutes(minutesToAdd);
        minutesToAdd++;
        return dt;
    });
    

    note that you could one-line the Returns(), but I always thought that unncessarily using pre or post increments is unreadable:

    DateTime.Now().Returns(x => dateToUse.AddMinutes(minutesToAdd++));