If you’re having trouble testing legacy code, mock a logger

I was working on some legacy code (“legacy” meaning it has no automated test coverage) and I really wanted to write some automated acceptance tests for it.  The problem is, I could not think of a way to do that without refactoring the code first.  I did not want to do this because “it was already working” and the refactoring could have introduced new bugs.  I had a chicken and egg problem: I didn’t want to modify code until I had automated tests but I had to modify code to write the automated tests.  Which comes first?

I ended up using a trick that minimally changes the production code, actually improves the production code base, and allows me to write automated tests.  It’s these two simple steps:

Continue reading

11 things I learned about TDD by looking at the tests in the JUnit source

JUnit is a unit testing framework for the Java programming language. JUnit has been important in the development of test-driven development, and is one of a family of unit testing frameworks which is collectively known as xUnit that originated with SUnit.

JUnit was originally written by Erich Gamma and Kent Beck. The latter literally wrote the book on Test Driven Development.  I thought it would be worthwhile to look at some of the tests in the library and draw attention to some interesting things about them because it may change people’s ideas of how to practice TDD.

Continue reading

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