我在测试System.Threading.Timer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);
重载方面已经挣扎超过一天。
基于this solution,我创建了实现了[[ITimer的ThreadingTimer,FakeTimer]:
public interface ITimer
{
bool Change(int dueTime, int period);
bool IsDisposed { get; }
void Dispose();
}
public class ThreadingTimer : ITimer, IDisposable
{
private Timer _timer;
public ThreadingTimer(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period)
{
_timer = new Timer(callback, state, dueTime, period);
}
public bool IsDisposed { get; set; }
public void Dispose()
{
IsDisposed = true;
Dispose();
GC.SuppressFinalize(this);
}
public bool Change(int dueTime, int period)
{
_timer.Change(dueTime, period);
return true;
}
}
public class FakeTimer : ITimer
{
private object state;
public FakeTimer(TimerCallback callback, object state)
{
this.state = state;
}
public bool IsDisposed { get; set; }
public bool Change(int dueTime, int period)
{
return true;
}
public void Dispose()
{
IsDisposed = true;
Dispose();
GC.SuppressFinalize(this);
}
}
在服务类中,我想使用我的[[ThreadingTimer:
public ITimer Timer { get; set; }
private void StartUpdates()
{
Task.Run(() =>
{
Timer = new ThreadingTimer(StartUpdatingVessels, null, TimeSpan.Zero, TimeSpan.FromHours(24));
}, Token);
}
但是,关于单元测试,我不知道并且不了解如何在FakeTimer
中利用和实现
ITimer的优势。因为如果在我的测试中将调用方法StartUpdates()
,则将创建ThreadingTimer的新实例,即使已经Timer道具已经分配了[[FakeTimer:
[Fact]
public void SetUpdatingStarted_CalledWhenUpdatingAlreadyStarted_DisposesTimer()
{
_timedUpdateControl.Timer = new FakeTimer(CallbackTestMethod, null);
bool intendedToStartUpdates = false;
_timedUpdateControl.StartOrStopUpdates(intendedToStartUpdates); //that methid calls private method StartUpdates() and creates instance for ITimer
//assert something
}
我如何在那儿嘲笑它? (我在测试项目中使用Moq框架)。 [Fact]
public void SetUpdatingStarted_CalledWhenUpdatingAlreadyStarted_DisposesTimer()
{
var timedUpdateControl = new TimedUpdateControl(new FakeTimer());
bool intendedToStartUpdates = false;
timedUpdateControl.StartOrStopUpdates(intendedToStartUpdates);
//assert something
}