遗留代码(通常是未经测试、难以修改的代码)很难进行测试——它可能有复杂的依赖关系且没有测试。安全地添加测试涉及特征化测试、使用接缝来打破依赖以及逐步改进等技术,从而能够更安全地进行更改。
遗留代码的挑战
Legacy code is often: untested, tightly coupled, hard to understand, risky to change:
→ no tests → changing it is dangerous (you can't tell if you broke something)
→ hard to test → dependencies are tangled (can't isolate units); not designed for testing
→ a chicken-and-egg problem: to change safely you need tests, but it's hard to test.
特征化测试(确定当前行为)
CHARACTERIZATION (golden master) tests → capture the code's CURRENT behavior as-is
(even if you don't fully understand it / it has bugs):
→ write tests asserting what it ACTUALLY does now → a SAFETY NET
→ then you can refactor/change with confidence that behavior is preserved
→ Don't assert what it SHOULD do — assert what it DOES, to protect against regressions.
