如何为秒表编写单元测试?
我有一个类,用于测量调用 Start
和 Stop
之间的时间。我创建了一个单元测试,在 Start
和 Stop
之间使用 boost::this_thread::sleep
进行睡眠,并且我测试结果是否接近时间睡了。
但是,此测试在我们的构建代理上失败,但在我们的开发机器上失败。问题是:我如何知道这是否是秒表的实际问题,或者是否是构建代理(运行一些其他进程,作为虚拟机)睡眠时间可能比我告诉它的时间长的“问题”?
所以问题是:是否有一种可靠的方法来编写类似“做某件事只需要 x 秒?”之类的内容?
多谢!
I have a class which measures the time between calling Start
and Stop
. I have created a unit test that sleeps using boost::this_thread::sleep
between Start
and Stop
and I test that the result is near the time slept.
However, this test fails on our build agent but not our development machines. The problem is: How do I know whether this is an actual problem of the stopwatch or if it's a "problem" that the build agent (running some other processes, being a virtual machine) might sleep longer than I told it to?
So the question: Is there a robust way to write something like "Do something that takes exactly x seconds?"
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有办法在非实时系统上可靠地测试这样的东西。解决的方法是包装用于获取秒表使用的系统时间的 API,并在测试中模拟它们。
There is no way to test something like this reliably on a non-realtime system. The way to go would be to wrap the APIs for getting the system-time that your stop-watch uses and mock them in the tests.
获取睡眠前后的系统时间,仅参考这些时间之间的差值,而不是您睡眠的时间。
Take the system time before and after the sleep and refer only to the difference between these times and not to the time you slept.
你的秒表的分辨率是多少?如果您需要精确到秒,那么可以睡 3 秒,看看是否在 2.9 到 3.1 之间。如果您需要毫/纳秒精度,您应该按照第一个回复中的建议使用时间戳模拟。
What is the resolution of your stopwatch? If you need to be accurate by seconds then sleeping for 3 seconds and seeing if you are between 2.9 and 3.1 will work for you. If you need mili/nano second accuracy you should just use timestamp mocks as suggestd in the first reply.
这取决于您使用的操作系统。在支持多道编程的系统上,线程的运行时间是不确定的。然而,在某些实时系统上,如果您的线程具有最高优先级,则几乎是准确的。您应该能够禁用中断来模拟这种情况,因为您的线程不会被操作系统调度程序抢占。
That depends on the operating system you're using. On systems that supports multi-programming, the running time of your thread is not deterministic. On some real-time systems however, it's almost accurate if your thread is of top priority. You should be able to disable the interrupt to simulate that case, because your thread will not be preempted by OS scheduler.