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.

2 Answers 2


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().

  • The time is indeed obtained via the System. The function method stores the loginTime and calculates elapsedTime via DateTime.Now - loginTime. I'll try to mock that into. Thanks for pointing me in that direction.
    – mhr
    Commented Feb 13, 2013 at 9:09
  • 5
    Then refactor it and replace every call to System.currentTimeMillis() with a method Time.now(), which usually does the same, but in test can be made to return any value you like. This can take some effort, but it's not likely to break anything, since it's a very focused and contained change. Commented Feb 13, 2013 at 9:11

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.

  • That's one of the things i'll head towards, but right now, elapsedTime is calculated within the function. I'm not sure if it's good to extract this without having a test for assuring the observable behaviour stays the same - what is crucial regarding to Fowlers Refactoring.
    – mhr
    Commented Feb 13, 2013 at 9:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.