Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

up vote 10 down vote accepted

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

share|improve this answer
    
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. –  mri Feb 13 '13 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. –  Kilian Foth Feb 13 '13 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.

share|improve this answer
    
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. –  mri Feb 13 '13 at 9:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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