您如何对内部使用计时器的类进行单元测试? [英] How do you unit test classes that use timers internally?

查看:31
本文介绍了您如何对内部使用计时器的类进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不管喜欢与否,有时您必须为内部使用计时器的类编写测试.

Like it or not, occasionally you have have to write tests for classes that make internal use of timers.

例如,一个类接收系统可用性报告并在系统停机时间过长时引发事件

Say for example a class that takes reports of system availability and raises an event if the system has been down for too long

public class SystemAvailabilityMonitor {
    public event Action SystemBecameUnavailable = delegate { };
    public event Action SystemBecameAvailable = delegate { };
    public void SystemUnavailable() {
        //..
    }
    public void SystemAvailable() {
        //..
    }
    public SystemAvailabilityMonitor(TimeSpan bufferBeforeRaisingEvent) {
        //..
    }
}

我有一些我使用的技巧(将发布这些作为答案)但我想知道其他人是怎么做的,因为我对我的任何一种方法都不完全满意.

I have a couple tricks which I use (will post these as an answer) but I wonder what other people do since I'm not fully satisfied with either of my approaches.

推荐答案

我从对警报做出反应的对象中提取计时器.例如,在 Java 中,您可以将它传递给 ScheduledExecutorService.在单元测试中,我传递了一个我可以确定性控制的实现,例如 jMock 的 DeterministicScheduler.

I extract the timer from the object that reacts to the alarm. In Java you can pass it a ScheduledExecutorService, for example. In unit tests I pass it an implementation that I can control deterministically, such as jMock's DeterministicScheduler.

这篇关于您如何对内部使用计时器的类进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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