Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you implement test driven development with legacy code?

The situation: millions of lines of code, more than one hundred developers and frequent defects. We want to avoid repeating defects and we want to improve code design (who doesn't?).

Test Driven Development (first unit test, then code) sounds ideal: write a test case for each function.

But, with so much code written, how can TDD be implemented? Where do you start - with low level functions?

Or are we too late to start TDD?

like image 843
Reinstate Monica - Goodbye SE Avatar asked Jul 08 '10 13:07

Reinstate Monica - Goodbye SE


Video Answer


2 Answers

Start with Working Effectively with Legacy Code.

It's not really TDD if you're starting with legacy code - but all your coding can be TDD. As you tackle a new problem, write a test for it. If you can't, because the legacy classes are too difficult to test, then start writing tests for them, slicing off bits, and covering the bits with tests.

Refactor the Low-Hanging Fruit.

To avoid repeating defects: given an example defect, write a test that demonstrates it. It could be a relatively broad test that just simulates user activity; not yet a unit test. Make sure the test fails. Do your research; figure out why the test is failing. Now - this is important - before fixing the bug, write a unit test that demonstrates the bug. Fix the bug, and now you've got two tests, at least one of them fast, that protect you from regressions.

like image 100
Carl Manaster Avatar answered Oct 02 '22 18:10

Carl Manaster


Since Carl suggested one book I'll suggest another: Roy Osherove's Art of Unit Testing has a whole chapter on "Working with legacy code". I haven't read that chapter yet, but the first 5 chapters are excellent, and I'm looking forward to it.

like image 35
orbfish Avatar answered Oct 02 '22 19:10

orbfish