问题
I am trying to follow TDD and am kind of new to it. I have a interface (Java) to be implemented.
So I started writing test cases for the interface behaviour, making them fail and fixing them by adding or modifying code.
However, as I see the main class is growing in size, I am breaking the main class into separate classes. But for some of the sub-classes, I realize that it's better to test them separately and mock them in the main class test cases.
But when I did that, I had to rewrite the main class test cases again (for the moved code) resulting in lots of churn and duplicate work.
Am I doing anything wrong in implementing the TDD methodology?
回答1:
It sounds like you're doing it about right. There are a couple of points to make, however. Restating to be sure we're on the same page:
To extract a helper class B from the main class A,
- refactor B out of A
- write tests for B (drawing on the tests for A)
- remove tests of A that are duplicated by tests of B
- if appropriate, rewrite the remaining test or tests of A that depend on functionality now in B to use a mock of B
Some advice:
After you've extracted the helper class, you can remove all but one (or maybe a few) of the tests of the main class that test helper class functionality. So you should not have many tests of the main class remaining that need to be rewritten.
For example, if the main class models a person and the helper class constructs the person's full name from their given name(s), surname, title, etc., the main class would originally have many tests of that functionality: one given name vs. more than one, title vs. no title, etc. You'd write equivalent tests for the helper class, then delete all but one of the main class tests that are about full name construction. You do need to leave one test in the main class that tests that it knows how to construct a full name of some kind; that test will fail if you mistakenly remove the call to the helper class or something like that.
If the helper class is simple (in particular, if it has no heavy dependencies that require special test setup or cause it to be slow), you don't have to mock it. That might save you some rewriting of main-class tests.
This process does require rework of tests as well as code. Minimize the rework by thinking ahead and doing the refactoring as soon as you convince yourself that it will be helpful. I find that when I think I need to extract a class I'm usually right; I rarely have to inline the class later. So being aggressive about extracting classes does not usually lead to extra work, but instead minimizes it by getting to the right object model sooner.
来源:https://stackoverflow.com/questions/37109329/in-tdd-splitting-main-class-into-sub-classes-during-refactoring