我是单元测试的新手,刚开始学习它。这是我要测试的代码。这是System.Threading.Timer的包装器,它不会泄漏异常。在此先感谢您的帮助。
<pre>
using System;
using System.Threading;
namespace MCC.Test.Unit
{
public class MyTimer : IDisposable
{
private static readonly TimeSpan NoAutoStartTimer = TimeSpan.FromMilliseconds(-1);
private readonly Object _synclock = new object();
private Timer _internalTimer;
public MyTimer()
{
_internalTimer = new Timer(TimerTick);
}
public MyTimer(Action tickHandler) : this()
{
Tick += tickHandler;
}
public void Dispose()
{
if (_internalTimer != null)
{
try
{
lock (_synclock)
{
_internalTimer.Dispose();
_internalTimer = null;
foreach (Delegate d in Tick.GetInvocationList())
{
Tick -= (Action) d;
}
}
}
catch (Exception err)
{
Console.Error.WriteLine(err);
}
}
}
/// <summary>
/// Called when the timer ticks
/// </summary>
public event Action Tick;
private void TimerTick(Object state)
{
try
{
if (Tick != null)
{
Tick();
}
}
catch (Exception err)
{
Console.Error.WriteLine(err);
}
}
/// <summary>
/// Schedules the next tick
/// </summary>
/// <param name="next">The duration until the next sprint</param>
public void TriggerNextTickIn(TimeSpan next)
{
try
{
lock (_synclock)
{
if (_internalTimer != null)
{
_internalTimer.Change(next, NoAutoStartTimer);
}
}
}
catch (Exception err)
{
Console.Error.WriteLine(err);
}
}
}
}
</pre>
答案 0 :(得分:0)
这里有很多要测试的地方:
Tick
是否来Tick
TriggerNextTickIn
将您的代码视为一个块框以及它所承诺的内容,并检查它是否符合该承诺。理想情况下,在完成代码本身之前编写测试...