Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding TDD making big refactorings harder [closed]

I'm still relatively a beginner in TDD, and I often end up into the trap where I've designed myself into a corner at some point when trying to add a new piece of functionality.

Mostly it means that the API that grew out of the, say, first 10 requirements, doesn't scale when adding the next requirement, and I realize I have to do a big redesign on the existing functionality, including the structure, to add something the new stuff in a nice way.

This is fine, except in this case the API would then change, so all the initial tests would then have to change. This is usually a bigger thing than just renaming methods.

I guess my question is twofold: How should I have avoided getting into this position in the first place, and given that I get into it, what are safe patterns of refactoring the tests and allowing new functionality with a new API to grow?

Edit: Lots of great answers, will experiment will several techniques. Marked as solution the answer I felt was most helpful.

like image 471
tddtrying Avatar asked Jan 21 '23 03:01

tddtrying


1 Answers

How should I have avoided getting into this position in the first place

The most general rule is: write tests with such refactorings in mind. In particular:

  • The tests should use helper methods whenever they construct anything API-specific (i.e. example objects.) This way you have only one place to change if the construction changes (e.g. after adding mandatory fields to the constructed object)

  • Same goes for checking the output of the API

  • Tests should be constructed as "diff from default", with the default provided by the above. For example if your test checks the effect of a method on field x, you should only set the x field in the test, with the rest of the fields taken from the default.

In fact, these are the same rules that apply to code in general.

what are safe patterns of refactoring the tests and allowing new functionality with a new API to grow?

Whenever you find out that an API change makes you change the tests in multiple places, try to figure out how to move the code into a single place. This follows from the above.

like image 87
Rafał Dowgird Avatar answered Feb 01 '23 16:02

Rafał Dowgird