In the course of a TDD session, suppose I write a failing test, and then make it pass. I refactor by extracting code out of the original Unit, using refactorings such as Extract Class and Move Method. Now further suppose that my original test no longer covers the extracted code because the original code now mocks out its dependencies, as is correct for a Unit test.
Is it proper to go back and retrofit tests onto the extracted code? Or did I make a mistake in how I ended up with untested code during a refactoring? It feels like as my codebase is scaling, and I have to refactor, I'm retrofitting a lot of tests onto refactored code. This feels really awkward. Am I refactoring wrong?
Now further suppose that my original test no longer covers the extracted code because the original code now mocks out its dependencies, as is correct for a Unit test.
Mocking dependencies is frequently a good thing to do, but not always, and I wouldn't say it's "correct for a unit test" to mock all dependencies.
In the refactoring step of TDD, you should be changing things in the production code that don't affect the passing of the tests. And you shouldn't be changing the tests at the same time.
You might want to later modify your tests so that the extracted code is tested independently of the original code and is mocked in the original tests.
This can be an indication that your unit tests are not fine-grained enough. Like, you've written integration test, made it pass, and now you're putting unit tests in place.
Or maybe after refactoring you are trying to put tests on something you shouldn't, such as private methods. Refactoring shouldn't change your code coverage anyway.
来源:https://stackoverflow.com/questions/5657433/how-to-handle-the-refactoring-phase-of-tdd