Platinum Partner
java,testing

Adding Unit Tests to Legacy Projects

While test driven development is widely accepted to be the best way to ensure quality in your project, not all projects start with this intention. In fact, some projects that you inherit may have no tests at all. These are the problem projects - you have a load of unfamiliar code in a legacy project that you're working on, and no tests. What's the best way to approach this?

The best suggestion that I have heard around this is fairly obvious, but it's worth repeating. As you add new features, functionality or bug fixes, make sure to write a unit test so that you can capture the state of the system before you add in your code. With a bug fix, you want to have a failing unit test setup; with additional functionality you'll want to ensure that you haven't broken anything after adding your changes. This incremental approach will eventually lead to you having more complete test coverage for your legacy application. 

Perhaps it's better to look at some key areas and think about writing up more complete test suites for those areas. How can we identify key areas? They would be: 

  • Parts of the code that get most 'traffic' from users / key use cases
  • Parts of code that have had a lot of bugs logged against it
  • And the biggest giveaway, critical code that looks complicated to you.
With experience, you get a gut feeling about the code that needs more testing.

These are just two of my approaches to adding a good test suite to your code. What are your suggestions for dealing with these zero-test projects? 

(JUnit is the most commonly used testing framework for Java applications, built into all the major IDEs. For those of you who have read this article, and are unsure about what to see what the basic JUnit test setup looks like, here's a really quick overview. DZone also provide this great refcard on JUnit & EasyMock. Also, if you're considering test driven development, I'd recommend the following cheat sheet[pdf].)

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}