简体   繁体   English

NSubstitute DateTime.Now() 如何让 DateTime.Now() 返回不断增加的日期和时间?

[英]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.我有几个单元测试,我们使用 NSubstitute 作为 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.在某些情况下,我想将 DateTime.Now() 增加一些设置量,以便每次调用它时,日期和时间都会增加一点。 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.每次调用 function 时都会返回 1/1/2/2018 00:01。
I thought the "AndDoes" would increment the minutesToAdd each time and would increase the time by one minute.我认为“AndDoes”每次都会增加 minutesToAdd 并将时间增加一分钟。
Can I get the DateTime substitute to increment by one minute each time it is called?我可以让 DateTime 替代品每次被调用时增加一分钟吗?

There should be an overload of Returns() that accepts a Func<,> , try it:应该有一个接受Func<,>Returns()重载,试试看:

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:请注意,您可以单行Returns() ,但我一直认为不必要地使用前置或后置增量是不可读的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM