In the simplest approach to using JUnit, you put all your tests in a subclass
of TestCase. Each test must be public, take no arguments, return
void, and have a method name beginning with the word “test.” Junit’s
reflection will identify these methods as individual tests and set up and run
them one at a time, taking measures to avoid side effects between the tests.
Feedback
Traditionally, the setUp( ) method creates and
initializes a common set of objects that will be used in all the tests; however,
you can also just put all such initialization in the constructor for the test
class. JUnit creates an object for each test to ensure there will be no side
effects between test runs. However, all the objects for all the tests are
created at once (rather than creating the object right before the test), so the
only difference between using setUp( ) and the constructor is that
setUp( ) is called directly before the test. In most situations this will
not be an issue, and you can use the constructor approach for simplicity. Feedback
If you need to perform any cleanup after each test (if you modify any statics
that need to be restored, open files that need to be closed, open network
connections, etc.), you write a tearDown( ) method.
This is also optional. Feedback
The following example uses this simple approach to create JUnit tests that
exercise the standard Java ArrayList class. To
trace how JUnit creates and cleans up its test objects, CountedList is
inherited from ArrayList and tracking information is added: Feedback
//: c15:JUnitDemo.java
// Simple use of JUnit to test ArrayList
// {Depends: junit.jar}
import java.util.*;
import junit.framework.*;
// So we can see the list objects being created,
// and keep track of when they are cleaned up:
class CountedList extends ArrayList {
privatestaticint counter = 0;
privateint id = counter++;
public CountedList() {
System.out.println("CountedList #" + id);
}
publicint getId() { return id; }
}
publicclass JUnitDemo extends TestCase {
privatestatic com.bruceeckel.simpletest.Test monitor =
new com.bruceeckel.simpletest.Test();
private CountedList list = new CountedList();
// You can use the constructor instead of setUp():
public JUnitDemo(String name) {
super(name);
for(int i = 0; i < 3; i++)
list.add("" + i);
}
// Thus, setUp() is optional, but is run right
// before the test:
protectedvoid setUp() {
System.out.println("Set up for " + list.getId());
}
// tearDown() is also optional, and is called after
// each test. setUp() and tearDown() can be either
// protected or public:
publicvoid tearDown() {
System.out.println("Tearing down " + list.getId());
}
// All tests have method names beginning with "test":
publicvoid testInsert() {
System.out.println("Running testInsert()");
assertEquals(list.size(), 3);
list.add(1, "Insert");
assertEquals(list.size(), 4);
assertEquals(list.get(1), "Insert");
}
publicvoid testReplace() {
System.out.println("Running testReplace()");
assertEquals(list.size(), 3);
list.set(1, "Replace");
assertEquals(list.size(), 3);
assertEquals(list.get(1), "Replace");
}
// A "helper" method to reduce code duplication. As long
// as the name doesn't start with "test," it will not
// be automatically executed by JUnit.
privatevoid compare(ArrayList lst, String[] strs) {
Object[] array = lst.toArray();
assertTrue("Arrays not the same length",
array.length == strs.length);
for(int i = 0; i < array.length; i++)
assertEquals(strs[i], (String)array[i]);
}
publicvoid testOrder() {
System.out.println("Running testOrder()");
compare(list, new String[] { "0", "1", "2" });
}
publicvoid testRemove() {
System.out.println("Running testRemove()");
assertEquals(list.size(), 3);
list.remove(1);
assertEquals(list.size(), 2);
compare(list, new String[] { "0", "2" });
}
publicvoid testAddAll() {
System.out.println("Running testAddAll()");
list.addAll(Arrays.asList(new Object[] {
"An", "African", "Swallow"}));
assertEquals(list.size(), 6);
compare(list, new String[] { "0", "1", "2",
"An", "African", "Swallow" });
}
publicstaticvoid main(String[] args) {
// Invoke JUnit on the class:
junit.textui.TestRunner.run(JUnitDemo.class);
monitor.expect(new String[] {
"CountedList #0",
"CountedList #1",
"CountedList #2",
"CountedList #3",
"CountedList #4",
// '.' indicates the beginning of each test:
".Set up for 0",
"Running testInsert()",
"Tearing down 0",
".Set up for 1",
"Running testReplace()",
"Tearing down 1",
".Set up for 2",
"Running testOrder()",
"Tearing down 2",
".Set up for 3",
"Running testRemove()",
"Tearing down 3",
".Set up for 4",
"Running testAddAll()",
"Tearing down 4",
"",
"%% Time: .*",
"",
"OK (5 tests)",
"",
});
}
} ///:~
To set up unit testing, you must only import junit.framework.* and
extend TestCase, as JUnitDemo does. In addition, you must create a
constructor that takes a String argument and passes it to its
super constructor. Feedback
For each test, a new JUnitDemo object will be created, and thus all
the non-static members will also be created. This means a new
CountedList object (list)will be created and initialized
for each test, since it is a field of JUnitDemo. In addition, the
constructor will be called for each test, so list will be initialized
with the strings “0”, “1”, and “2” before each test is run. Feedback
To observe the behavior of setUp( ) and tearDown( ), these
methods are created to display information about the test that’s being
initialized or cleaned up. Note that the base-class methods are
protected, so the overridden methods may be either protected or
public. Feedback
testInsert( ) and testReplace( ) demonstrate typical test
methods, since they follow the required signature and naming convention. JUnit
discovers these methods using reflection and runs each one as a test. Inside the
methods, you perform any desired operations and use JUnit assertion methods
(which all start with the name “assert”) to verify the correctness of your tests
(the full range of “assert” statements can be found in the JUnit javadocs for
junit.framework.Assert). If the assertion fails, the expression and
values that caused the failure will be displayed. This is usually enough, but
you can also use the overloaded version of each JUnit assertion statement and
include a String that will be printed if the assertion fails. Feedback
The assertion statements are not required; you can also just run the test
without assertions and consider it a success if no exceptions are thrown. Feedback
The compare( ) method is an example of a “helper” method that is not
executed by JUnit but instead is used by other tests in the class. As long as
the method name doesn’t begin with “test,” JUnit doesn’t run it or expect it to
have a particular signature. Here, compare( ) is private to
emphasize that it is only used within the test class, but it could also be
public. The remaining test methods eliminate duplicate code by refactoring it
into the compare( ) method. Feedback
To execute the JUnit tests, the static method TestRunner.run( ) is
invoked in main( ). This method is handed the class that contains the
collection of tests, and it automatically sets up and runs all the tests. From
the expect( ) output, you can see that all the objects needed to run all
the tests are created first, in a batch—this is where the construction
happens.[92] Before each test, the
setUp( ) method is called. Then the test is run, followed by the
tearDown( ) method. JUnit demarcates each test with a ‘.’. Feedback
Although you can probably survive easily by only using the simplest approach
to JUnit as shown in the preceding example, JUnit was originally designed with a
plethora of complicated structures. If you are curious, you can easily learn
more about them, because the JUnit download from www.JUnit.org comes with
documentation and tutorials. Feedback