This can't be answered in general because itThe primary benefit of unit tests is perfectly possible to write well-designed codeallow safe refactoring without having unit testsintroducing bugs or unexpected changes in behavior. IfSafe refactoring is crucial to allow a codebase to change and grow while remaining maintainable.
But the code already has those qualities,process of adding unit tests to existing code is unlikely to find many bugs because unless you have a very detailed specification you would not in itself changeprobably end up assuming the quality ofexisting behavior is the tested codeexpected behavior. And design principles like SOLID does not in themselves eliminate bugs (although they might make bugs easier to detectThe benefit comes after the tests have been added and fix)you start refactoring.
It is also problematic to rely on refactoring to support test-ability tosometimes argued that making code testable in itself will improve the quality of the code because any refactoring carries the risk of introducing errorsquality. Indeed,This is a major purpose ofdubious argument for several reasons:
- It is quite possible to have code following good design principles without having tests. So the argument would imply that adding unit tests to code which is already well-designed would not provide value.
- While testability implies some aspects of code quality there are many aspects which is not affected. So testability is not sufficient as a driver of code quality.
- If making the code testable requires refactoring, those refactorings are likely to introduce bugs which will negate the purported benefit.
If you have low code quality and code not amenable to unit tests is to make refactoring safer. So if, you refactorneed a different approach: You should add integration tests or end-to-end tests which verify the behavior of the system before adding tests, you are missing the point of testing.
The correct way to approach legacy code isdo any refactoring to add automatedsupport unit tests before refactoring.