Chapter 1. JUnit Pocket Guide

Automating Tests

Nearly every programmer tests his code. Testing with JUnit isn’t a totally different activity from what you’re doing right now. It’s a different way of doing what you’re already doing. The difference is between testing, that is checking that your program behaves as expected, and having a battery of tests, little programs that automatically check to ensure that your program behaves as expected. In this chapter we’ll go from typical println( ) -based testing code to a fully automated test.

Let’s begin writing our first automated test. Imagine that we have been asked to test Java’s built-in ArrayList. One bit of functionality to test is the method length ( ). When we create a new list it should have a length of 0. After we add an element the length should be 1. Imagine a little code snippet to test this:

List fixture= new ArrayList(  );
// fixture should be empty
Object element= new Object(  );
fixture.add(element);
// fixture should have one element

Tip

How do you pick good data values for tests? My habit is to pick a few representative values and to choose values that result in easy-to-check results. If I’m testing a currency converter, for example, an exchange rate of 2:1 is just as valuable as a programming tool as a “realistic” rate of 1.32471:1. For collections, like the one here, no elements and one element may be sufficient. Use induction to simplify testing. If “zero and one element work” implies “any number of elements work,” use zero ...

Get JUnit Pocket Guide now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.