带超时的单元测试 [英] Unit testing with timeouts

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

问题描述

我正在对一个类的属性进行单元测试,该属性的值经常发生变化,具体取决于它从另一个组件接收到的通信.如果该类在 5 秒内未收到任何通信,则该属性将恢复为默认值.

I am unit testing a class with a property whose value changes often, depending on communication it receives from another component. If the class does not receive any communication for 5 seconds, the property reverts to a default value.

我很容易对通信组件进行存根和模拟,以触发我想要测试的值.问题是,如果我在繁忙的机器(如构建机器)上运行我的单元测试,并且有足够长的延迟导致属性默认,那么我的单元测试将失败.

It is easy for me to stub and mock out the communicating component in order to trigger the values I want to test for. The problem is that if I run my unit tests on a machine which is busy (like a build machine), and there is a significant-enough delay to cause the property to default, then my unit test will fail.

在模拟各种通信条件时,您将如何测试以确保此属性具有正确的值?

一个想法是重构我的代码,以便我可以存根控制超时的类部分.另一个是编写我的单元测试,以便它可以检测是否由于超时而失败,并在测试结果中指出.

One idea is to restructure my code so that I can stub the part of the class which controls the timeout. Another is to write my unit test such that it can detect if it failed due to a timeout and indicates that in the test results.

推荐答案

您可以使超时属性可配置,然后在您的单元测试中将其设置为足够高的值(或足够低,如果您想对重置进行单元测试行为).

You could make the timeout property configurable, then set it to a high enough value in your unit tests (or low enough, if you want to unit test the reset behaviour).

这篇关于带超时的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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