Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a unit test for a stopwatch?

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!

like image 747
Philipp Avatar asked Dec 06 '25 08:12

Philipp


1 Answers

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.

like image 124
Björn Pollex Avatar answered Dec 08 '25 22:12

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!