If the amount you sleep does not matter for the test, and you can set me to 1 millisecond, then it should be good to just sleep for 1 millisecond in your test.
However, if you want to test complex temporal behavior with timeouts and specific actions taken at specific points in time, it quickly becomes easier to abstract from the concept of time and introduce it as a dependency. Then your tests can run in virtual time and run without delay, even if the code works as if it were passing in real time.
An easy way to virtualize time is to use something like this:
interface ITimeService { DateTime Now { get; } void Sleep(TimeSpan delay); } class TimeService : ITimeService { public DateTime Now { get { return DateTime.UtcNow; } } public void Sleep(TimeSpan delay) { Thread.Sleep(delay); } } class TimeServiceStub : ITimeService { DateTime now; public TimeServiceStub() { this.now = DateTime.UtcNow; } public DateTime Now { get { return this.now; } } public void Sleep(TimeSpan delay) { this.now += delay; } }
You will need to expand on this idea if you need more reactive behavior, such as triggering timers, etc.
Martin liversage
source share