Home > Articles > Programming

  • Print
  • + Share This
From the author of

When Should We Add Tests?

The crux of the problem is that code tested well in its original context may not work in a new context. There are times when you might adjust your tests.

One approach is not to worry about it. Trust that your tests of new features will catch any uses of code refactored to a new context. This rule has the advantage that it's easy to follow, but it may not be as safe as a more aggressive approach. You'll need to be sensitive to how well your tests are finding problems.

Another approach is to add tests when you use a class in a new way. When you refer to a class, see whether its tests seem to cover the new context you plan to use. If not, beef up the tests before you add code. This practice lets you create new tests "just in time," but the rule requires discipline to work.

The most aggressive approach is to add and change tests just after you refactor. It may seem that this would be a hard discipline to follow, but I've found it easier to do it this way than the previous approaches. When adding new code, I find I don't want to stop and backfill tests, but I'm in a more reflective mood when I'm refactoring.

You can choose between these approaches on a case-by-case basis, but pay attention to the feedback you get: Do manual refactorings cause problems, especially ones that don't show up for a while? Do you find problems when using code in a new context? Do your tests miss any problems? If so, improve the discipline of your testing.

  • + Share This
  • 🔖 Save To Your Account