I’m currently in the middle of refactoring an important method in a legacy-system. There were almost zero test until I’ve started working on it, and I’ve added quite a lot to ensure the correct work after my refactorings.
Now I’ve came across the most crucial part: the algorithm that calculates an indicator. It’s something like
indicator = (OneNumberFromA + AnotherNumberFromB) / elapsedTime;
How can I test the correct behavior for this Function with Unit tests?
There are also some slightly different algorithms in the functions, that the program reaches in some cases – but in all of them, the elapsedTime
is vital to the outcome.
The same way you solve almost every issue with unit tests: you mock the elapsed time.
I advise using a standardized method to obtain the system time throughout a system, and then making that method overridable, so your unit tests have total control. The tests will then contain lots of nifty calls like Time.fake(timeA)
, or even Time.stop()
.
2
Time measurement & indicator evaluation should be in different functions. In your case, elapsedTime
should be an input of the evaluation function. That way, your evaluation code can be tested, and is easier to understand.
Now you still have the problem of testing the time measurement function, but this is beyond the scope of this question.
1