# Java Notes

# JUnit and Test-Driven Development

## Test-Driven Development

One of the big changes in software engineering, and part of the agile methodology shift, is Test Driven Development (TDD). This puts writing tests near the front of the development process, not at the end as in older methodologies.

Tests contribute to design. Experience with TDD has shown that writing the tests first has many benefits, but an important one is that it contributes to the design process. Thinking about what to test involves thinking about how the program works.

Confidence to make changes. Another advantage is that once you have a lot of tests, you're much less afraid to improve ("refactor" in the current jargon) code. Make a few changes, then rerun the tests.

See en.wikipedia.org/wiki/Test_driven_development for more.

## JUnit - an automated testing tool

To make TDD easy, a number of frameworks have been written. The most popular, and indeed the de facto, tool for Java is JUnit (www.junit.org). JUnit is hugely popular with support in all the IDEs.

As Elliotte Harold (author of many good Java books) said,

> JUnit, developed by Kent Beck and Erich Gamma, is almost indisputably the single most important third-party Java library ever developed.

## Where to find out more

There is an abundance of online material. The JUnit site has many links to introductory material, including the following: JUnit Test Infected: Programmers Love Writing Tests. It's also covered in many books.

## Using JUnit is easy

Using JUnit is quite easy; there are only a few things to learn. NetBeans makes it even easier by automatically doing most of the work for you. You can get either GUI or text feedback on how your tests performed. There's a lot of pleasure in seeing the green bars grow in the GUI output, but in an attempt to keep things really simple, it appears that JUnit version 4 will support only text output. The authors of JUnit are dedicated to simplicity in programs, so this removal of features is a wonderful contrast to normal bloatware.

## Good alternatives

Altho JUnit has been the most popular unit testing tool, others are available. See Justin Lee's Test Framework Comparison (www.theserverside.com/articles/content/TestFrameworkComparison/article.html) compares three of them.

These newer test frameworks make use of Java 5 annotations. The JUnit authors have not been sleeping, and JUnit 4 also makes use of annotations. The above review was written before the release version of JUnit 4 was available, so it isn't compared in the article.