1

在一个项目中,我们的系统使用 nservicebus 超时每 24 小时触发一次事件。是否有可能通过单元测试“伪造” 24 小时,以便可以在任何给定时间运行测试,从而不必等待一天才能运行测试?

重写的超时方法如下所示:

public override void Timeout(object state)
{
ExportFileGenerator.GenerateFile(_entryDataStore.GetEntriesOlderThan(DateTime.Now));
RequestUtcTimeout(TimeSpan.FromHours(TimeLeftToDailyJob()), "");
}
4

2 回答 2

3

我在这里写了一篇关于如何做到这一点的博客:

http://www.udidahan.com/2012/02/27/nservicebus-saga-tips/

于 2012-06-11T18:38:47.030 回答
1

You simply do that by extracting dependency on time-related services (in your case, that would be TimeLeftToDoDailyJob method).

There're basically two ways to achieve that:

  • make the method virtual and prepare testable version of your class with that method returning some very small (unnoticable) value
  • extract that method to brand new class and inject instance of such class as a dependency to your tested class (inversion of control with constructor injection)

I'd go for second approach as it usually forces more decoupled design, which leads to less complex code and as a result - easier tests.

于 2012-06-11T06:48:26.207 回答