Jakub Arnold

Refactoring Tips: Don't Trust Your Unit TestsMay 7, 2014

Before you start making any changes, make sure you have an integration test covering the part of the application you’re changing. While unit tests might be useful on a small scale refactorings, they usually break if you change the layout of your code, even a little bit. This is mostly because a big portion of the unit tests will depend on the exact API of your classes, instead of their behavior.

Once you start changing multiple classes and how they interact it will become harder and harder to rely on the unit tests. When they break it basically forces you to either ignore them, in which case they don’t provide much value, or fix them, in which case they don’t tell you if the original functionality still works.

On the other hand, having a test that goes through your whole application and verifies that things are wired up properly can easily give you enough confidence to keep refactoring further. It is important to have at least some verification that things aren’t completely broken.

This might be a bit different from the usual TDD cycle, where you’re supposed to refactor after every small iteration of red-green-refactor. The reason is that when you have a big application, you’re sometimes forced to make a big change at once. No matter how many best practices you follow or how many patterns you use, there will be a time when you can’t use any of them. The biggest the application is the more likely you will be forced to take drastic measures to fix things.

The best practices developers have are useful, but you need to learn to let them go from time to time. Sometimes you need to get your hands dirty, break all of your unit tests, or even delete them, and keep that single integration spec in your mind to have enough confidence to keep going. Because what really matters is that your application is still working, not that you have 1000 unit tests that don’t prove anything.

I’m not saying unit tests are bad. They just aren’t all that useful when you’re refactoring the layout of your classes, or redesigning your application if you will.

Want to hear about my upcoming book,
Haskell by Example?

Haskell by Example Book

Subscribe to receive updates and free content from the book. You'll also get a discount when the final version of the book is released.