.NET 中的单元测试 System.Threading.Timer [英] Unit test System.Threading.Timer in .NET
问题描述
如何在 .NET 中对基于 System.Threading.Timer 的计时器进行单元测试System.Threading.Timer 有一个回调方法
How to unit test a timer based on System.Threading.Timer in .NET The System.Threading.Timer has a callback method
推荐答案
您可以通过不实际创建对 System.Threading.Timer
的直接依赖来对其进行单元测试.相反,创建一个 ITimer
接口,以及一个实现它的 System.Threading.Timer
的包装器.
You can unit-test it by not actually creating a direct dependency on System.Threading.Timer
. Instead, create an ITimer
interface, and a wrapper around System.Threading.Timer
that implements it.
首先,您需要将回调转换为事件,以便将其作为接口的一部分:
First you need to convert the callback to an event, so that it can be made part of an interface:
public delegate void TimerEventHandler(object sender, TimerEventArgs e);
public class TimerEventArgs : EventArgs
{
public TimerEventArgs(object state)
{
this.State = state;
}
public object State { get; private set; }
}
然后创建一个接口:
public interface ITimer
{
void Change(TimeSpan dueTime, TimeSpan period);
event TimerEventHandler Tick;
}
还有一个包装器:
public class ThreadingTimer : ITimer, IDisposable
{
private Timer timer;
public ThreadingTimer(object state, TimeSpan dueTime, TimeSpan period)
{
timer = new Timer(TimerCallback, state, dueTime, period);
}
public void Change(TimeSpan dueTime, TimeSpan period)
{
timer.Change(dueTime, period);
}
public void Dispose()
{
timer.Dispose();
}
private void TimerCallback(object state)
{
EventHandler tick = Tick;
if (tick != null)
tick(this, new TimerEventArgs(state));
}
public event TimerEventHandler Tick;
}
显然,您可以从 Threading.Timer
添加任何需要使用的构造函数和/或 Change
方法的重载.现在,您可以根据 ITimer
使用伪计时器对任何内容进行单元测试:
Obviously you would add whatever overloads of the constructor and/or Change
method you need to use from the Threading.Timer
. Now you can unit test anything depending on ITimer
with a fake timer:
public class FakeTimer : ITimer
{
private object state;
public FakeTimer(object state)
{
this.state = state;
}
public void Change(TimeSpan dueTime, TimeSpan period)
{
// Do nothing
}
public void RaiseTickEvent()
{
EventHandler tick = Tick;
if (tick != null)
tick(this, new TimerEventArgs(state));
}
public event TimerEventHandler Tick;
}
每当你想模拟一个滴答声时,只需在假上调用 RaiseTickEvent
即可.
Whenever you want to simulate a tick, just call RaiseTickEvent
on the fake.
[TestMethod]
public void Component_should_respond_to_tick
{
ITimer timer = new FakeTimer(someState);
MyClass c = new MyClass(timer);
timer.RaiseTickEvent();
Assert.AreEqual(true, c.TickOccurred);
}
这篇关于.NET 中的单元测试 System.Threading.Timer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!