unit-testingtddsolid-principlesopen-closed-principle

How do Test-Driven Development and the Open/Closed Principle work together?


I've been reading up on unit testing, TDD, and the SOLID principles and I need some clarification. My understanding is that if one adheres to the open/closed principle, unit testing could become largely unnecessary due to the fact that the code is closed to modification - thus there is no need to retest if the code is properly isolated and decoupled. The longterm benefit of the added upfront cost of unit testing is lost if once the code passes related unit tests it will not change. The code will always pass because it will never change, right? Inherited classes will need to be tested, but once they pass related tests, they too will be closed to modification and will not need to be retested. The Wikipedia article on OCP reinforces this line of thought in the first paragraph, (I realize that doesn't make it law).
The best explanation I've found for OCP and TDD living in harmony is here, though it seems that Arnon is saying that OCP compliments TDD in that the developer is discouraged from modifying source code because existing test methods can become complex when modified to test new functionality.
Is that all there is to it? Mind you that I'm not looking for an argument, I'm new to this and I'm looking for clarification from those with more experience with the subject than I.


Solution

  • Even if you were to accept that once software works and doesn't change, you don't need to test it (which I don't), you still need to show that a component works in the first place. I would argue one of the best ways to do that is a unit test(s).

    Also, practically speaking, once you have the test, it costs very little to run it. So even if components don't change, you aren't losing much by continually running the tests. Furthermore, sometimes design changes and you need to go back and redo some components -- having unit tests definitely helps in this case...

    Remember, one result of having a test suite is that it promotes maintainability by showing when something changes. So even if your team is following the O in SOLID, that doesn't mean that things won't get changed accidentally. So the tests help there by showing if something is changed inadvertently, and they show you exactly what was affected by the change.