在.NET单元测试System.Threading.Timer [英] Unit test System.Threading.Timer in .NET

查看:200
本文介绍了在.NET单元测试System.Threading.Timer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行单元测试的基于.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; }
}

然后创建一个接口:

Then create an interface:

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 。现在,您可以单元测试任何根据 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 上的假货。

[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆