What I say here isn’t original, but maybe you’ll find it useful. I wrote it for today’s C# Unit Testing chat.
Q: I’m quite new to TDD – are there any best practices for retrofitting existing code with unit test. A huge task.
A: A common question, and a difficult one to answer, for sure.
I would start by searching google for the topic. There has been a lot of discussion on this topic on Wikis and on the TDD Yahoo Group.
The broad strokes go like this:
- Apply some automated behavioral tests. Try to hit the code that you’re going to work on.
- Start refactoring that code to pull out the big chunks. Add more tests as needed to do this confidently.
- As big chunks become decoupled, you can start writing Unit Tests for them.
- As the Unit Test coverage gets better, you can refactor with increased confidence.
Keep your eye on the ball. Your goal here is to get tests around the code you intend to change for the customer’s benefit. Refactoring or building unit tests for code you don’t intend to change isn’t valuable.