Testing Legacy Code Before Refactoring: A Step-by-Step Guide
This guide shows you how to write tests for legacy code before you refactor it, so you can change behavior with confidence and catch regressions early. You’ll learn a practical, incremental approach that works even when the code is messy, undocumented, or tightly coupled. You’ll start by identifying the seams and behaviors you need to protect, then write characterization tests that lock in current behavior, and finally refactor with a safety net in place.
What You’ll Need
- A legacy codebase you can run (or at least compile) — you need to execute the code to see what it does.
- A test framework for your language (e.g., JUnit, pytest, NUnit, Jest). If none exists, set up a minimal one.
- A way to run a single test or a small subset of tests quickly — this is critical for fast feedback.
- Access to the code’s inputs and outputs — either through public methods, command-line arguments, or configuration files.
- Version control (like Git) so you can revert if something goes wrong.
Step-by-Step
- Identify the behavior you want to preserve. Start with the highest-risk or most-used parts of the code — the functions that are called often or that you plan to change. List the key inputs and expected outputs for each.
- Find the seams. Look for places where you can call the code without modifying it — a public method, a command-line entry point, or a function that takes simple parameters. If the code is tightly coupled to a database or network, use dependency injection or a test double to isolate it, but only if that doesn’t require changing the production code yet.
- Write a characterization test. For each behavior you identified, write a test that calls the code with a known input and asserts the actual output. You don’t need to know if the output is correct — you’re capturing what the code does today. For example, if a function returns 42 for input 7, write a test that expects 42.
- Run the test and record the result. If the test passes, great — you’ve locked in that behavior. If it fails, the code may have side effects or the test setup is wrong. Fix the test setup, not the code. If the code throws an exception, capture that as the expected behavior (e.g., assert that it throws).
- Add tests for edge cases. For each function, test boundary values, null/empty inputs, negative numbers, and any special cases you can think of. You don’t need to test every possible input — just the ones that are likely to break during refactoring.
- Group tests by behavior, not by method. If a method has multiple responsibilities, write separate tests for each. This makes it easier to see what you’re protecting and what might change.
- Run the full suite and commit. Once you have a set of passing tests, commit them to version control. This is your safety net. Now you can refactor with confidence — if you break something, the tests will tell you.
- Refactor in small steps. Make one change at a time, run the tests after each change, and keep the tests green. If a test fails, revert the change and try a different approach.
Common Mistakes
- Writing tests that assert the wrong thing. Characterization tests should assert the actual behavior, not what you think the behavior should be. If you write a test expecting the “correct” output, it will fail and you’ll be tempted to fix the code — that’s not the goal yet.
- Trying to test everything at once. Legacy code can be huge. Focus on the parts you’re about to refactor. You can add more tests later.
- Refactoring before you have tests. The whole point is to have a safety net first. If you refactor first, you’ll be guessing whether you broke something.
- Ignoring side effects. If the code writes to a database or a file, your test will affect that. Use test doubles or temporary directories to isolate side effects, or at least be aware of them.
- Not committing after writing tests. If you don’t commit, you might lose your work or forget what you tested. Commit early and often.
Tips
- Use a code coverage tool to see which lines your tests execute. Aim for high coverage on the code you’re about to change, but don’t obsess over 100% — focus on critical paths.
- Write tests that are easy to read. Use descriptive test names like
test_calculate_total_with_discountso you know what behavior is protected. - If the code is hard to test, that’s a signal. It may be a sign that you need to refactor to make it testable, but do that after you have some characterization tests in place.
- Keep tests independent. Each test should set up its own data and not rely on other tests running first. This makes it easier to run a single test when something fails.
- Use a test runner that shows you a diff when a test fails. This helps you see exactly what behavior changed.
Troubleshooting
Test fails even though the code hasn’t changed. This usually means your test setup is wrong — maybe the input isn’t what you think, or the code has side effects that affect the result. Double-check the input and the expected output. If the code uses global state, reset it in the test.
You can’t run the code at all. If the legacy code is so broken that it won’t compile or run, you have a bigger problem. Start by fixing the build, but don’t refactor — just make it runnable. Once it runs, you can write tests.
The code is too tightly coupled to test. If you can’t call a function without setting up a database or a network connection, look for a seam — maybe you can call a smaller internal function, or you can use reflection to access private methods (as a last resort). If that’s impossible, you may need to do a small refactor first to introduce a seam, but do it carefully and manually verify the behavior.
Your tests pass but the refactoring still breaks something. This means you missed some behavior. Add more tests for edge cases or different inputs. Also, consider testing at a higher level — integration tests that exercise multiple functions together can catch issues that unit tests miss.
Frequently Asked Questions
Q: What if the legacy code has bugs? Should I test the buggy behavior?
A: Yes, for now. Your goal is to preserve current behavior so you can refactor safely. Once you have tests, you can fix bugs deliberately — the tests will help you see what changes.
Q: How many tests do I need before I can refactor?
A: Enough to cover the behavior you’re going to change. If you’re refactoring a function, test all its inputs and edge cases. If you’re refactoring a whole module, test each public method. You don’t need exhaustive coverage of the entire codebase.
Q: Can I write tests after I start refactoring?
A: It’s riskier, but possible. If you’re already in the middle of a change, stop, write tests for the current state, then continue. The tests will still help you catch regressions.
Q: What if the code is written in a language with no test framework?
A: You can still write simple assertion scripts that run the code and check outputs. Many languages have built-in assert statements. Or you can use a lightweight test harness that you write yourself.
Q: Should I test private methods?
A: Generally no — test through public interfaces. But if a private method contains critical logic and is hard to reach, you can use reflection or make it package-private for testing, but that’s a last resort. Prefer testing the public behavior.
Q: What if the code is so tangled that I can’t even identify the inputs and outputs?
A: Start with the simplest thing: run the program with a known input and observe the output. That’s your first characterization test. Then gradually add more. You can also use logging or a debugger to trace what’s happening.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.