'How should I write unit tests for a method uses timer?
I've written a method that waits for 5 seconds, how should I write unit tests for it to ensure that it has waited for 5 seconds?
public IObservable<Unit> Wait(CancellationToken token)
{
var unit = Observable.Return(Unit.Default);
lock (Locker)
{
if (Waited)
return unit;
Waited= true;
unit = Observable.Timer(TimeSpan.FromSeconds(5))
.Select(_ => Unit.Default)
.RunAsync(token);
}
return unit;
}
Solution 1:[1]
You can use the StopWatch class to measure time or just take current time before and after the method is called and assert that 5 seconds or more passed.
For example:
using Shouldly;
var watch = StopWatch.StartNew();
Wait() // call your function
watch.stop();
watch.Elapsed.Seconds.ShouldBeGreaterThanOrEqualTo(5);
or
Assert.IsTrue(watch.Elapsed.Seconds> 5, "The time was not greater than five");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MC LinkTimeError |
