How does TDD make refactoring easier?

前端 未结 8 1158
温柔的废话
温柔的废话 2021-02-01 16:53

I\'ve heard that projects developed using TDD are easier to refactor because the practice yields a comprehensive set of unit tests, which will (hopefully) fail if any change has

8条回答
  •  情书的邮戳
    2021-02-01 17:20

    One thing you need to keep in mind is that TDD is not mainly a testing strategy, but a design strategy. You write the tests first, because that helps you come up with a better decoupled design. And a better decoupled design is easier to refactor, too.

    When you change the funcionality of a class or method, it's natural that the tests have to change, too. In fact, following TDD would mean that you change the tests first, of course. If you have to change a lot of tests to just change a single bit of functionality, that typically means that most tests are overspecifying the behavior - they are testing more than they should test. Another problem could be that a responsibility isn't well encapsulated in your production code.

    Whatever it is, when you experience many tests failing because of a small change, you should refactor your code so that it doesn't happen again in the future. It's always possible to do that, though not always obvious how to.

    With bigger design changes, things can become a bit more complicated. Yes, sometimes it will be easier to write new tests and discard the old ones. Sometimes, you can at least write some integration tests that test the whole part that gets refactored. And you hopefully still have your suite of acceptance tests, that are mostly unaffected.

    I haven't read it yet, but I have heard good things about the book "XUnit Test Patterns - Refactoring Test Code".

提交回复
热议问题