How to write your automated tests so they don’t fail when you refactor

The main benefit of a good automated test suite is that it gives you confidence that your code is working correctly.  It helps you find bugs as soon as you introduce them instead of at 3am on a production environment.

If you have a solid test suite, you can feel confident that the change you made is safe.  When you have that confidence, it allows you to change the nastiest parts of your code without wondering if you broke something.

But sometimes tests can get in your way.  Sometimes you’ll want to refactor a group of classes and tests will fail even though nothing actually broke.  This is a bad smell and it should be avoided.  In this article I’m going to teach you how.  But, before I do that, I want to make sure we all agree on the definition of “refactoring”.

Code refactoring is the process of restructuring existing computer code – changing the factoring – without changing its external behavior. –Wikipedia

In other words, refactoring means cleaning up the code without changing functionality.  If you refactored correctly, every single feature in your application should work exactly the same as it did before you refactored.

Here’s how you know you’ve got a problem

Continue reading