Possible Duplicate:
Best practices for retrofitting legacy code with automated tests

When working in large legacy systems (large systems with no unit testing ever) I often come across people saying use unit testing as a tool against possible bugs. I wonder if somebody have tried it on large systems with no unit testing at all.

Of course it is easy to say unit testing helps ,but in large systems it can hugely time consuming process. It can take months if not years to fully unit test each part of the application .

When you are asked to make a functionality which is modification of existing functionality or adding new functionality to the application, how would you go about it? Of course there will be lots of instances where code in different classes will look similar and you would want to re-factor those classes which without proper unit testing can and most likely will open a can of worms.

So how would you go about unit testing large applications? And what other measures would you use to reduce possible bugs from your coding (of course some bugs will probably remain anyway)?


1 Answer 1


Covering legacy code with unit tests is a long, difficult, step by step process. But it is doable, and is an absolute must if you are maintaining a product with a long expected lifetime (i.e. more than a year - note that the lifetime of most project significantly extends their originally planned lifetime).

When I joined our current project close to 3 years ago, there existed less than 50 unit test cases and the coverage was below 0,5%. Around the end of last year, we had over 2600 unit tests and coverage was over 36%. (Since then development has been largely stalling.) During the same time, code size went down from 106 to 67 KLOC, and technical debt (as measured by Sonar) from over $513K to $213K - while new functionality was added too.

So yes, it is possible. But only with a management that supports code quality improvement and long term maintainability, and is willing to spend significant time and resources on it.

If you have such a management, my first advice is: run, don't walk, to buy Working Effectively With Legacy Code by Michael Feathers.

Then start adding unit tests. The simplest tactic is to add unit tests before you need to touch any part of the code, to cover the changing part(s) to some reasonable extent. Sometimes you just add a single test case at a time to cover a simple change in a huge class. Sometimes you have more time, so you can construct a more comprehensive test suite to fully cover a bigger method, or even several of them. Keep adding unit tests - the little changes will add up to ever greater sums in the long term.

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