【发布时间】:2023-03-05 09:49:01
【问题描述】:
我是单元测试的新手,刚刚开始学习它。这是我要测试的代码。这是 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>
【问题讨论】:
-
您的问题是什么?如果您只是在寻找代码审查,也可以查看 codereview.stackexchange.com
-
问题是如何检查计时器是否计时,谢谢
标签: c# unit-testing testing nunit