Java Reference
In-Depth Information
Solution
Use unit testing to validate each class as you develop it.
Discussion
Stopping to use a debugger is time consuming; it's better to test beforehand. The methodo-
logy of unit testing has been around for a long time; it is a tried-and-true means of getting
your code tested in small blocks. Typically, in an OO language like Java, unit testing is ap-
plied to individual classes, in contrast to “system” or “integration” testing where the entire
application is tested.
I have long been an advocate of this very basic testing methodology. Indeed, developers of
the software methodology known as Extreme Programming (XP for short) advocate “Test
Driven Development” (TDD): writing the unit tests before you write the code. They also ad-
vocate running your tests almost every time you build your application. And they ask one
good question: If you don't have a test, how do you know your code (still) works? This group
of unit-testing advocates has some well-known leaders, including Erich Gamma of Design
Patterns book fame and Kent Beck of eXtreme Programming book fame. I definitely go
along with their advocacy of unit testing.
Indeed, many of my classes used to come with a “built-in” unit test. Classes that are not main
programs in their own right would often include a main method that just tests out the func-
tionality of the class. What surprised me is that, before encountering XP, I used to think I did
this often, but an actual inspection of two projects indicated that only about a third of my
classes had test cases, either internally or externally. Clearly what is needed is a uniform
methodology. That is provided by JUnit .
JUnit is a Java-centric methodology for providing test cases that you can download for free .
JUnit is a very simple but useful testing tool. It is easy to use—you just write a test class
that has a series of methods and annotate them with @Test (the older JUnit 3.8 required you
to have test methods' names begin with test ). JUnit uses introspection (see Chapter 23 ) to
find all these methods, and then runs them for you. Extensions to JUnit handle tasks as di-
verse as load testing and testing enterprise components; the JUnit website provides links to
these extensions. All modern IDEs provide built-in support for generating and running JUnit
tests.
Search WWH ::




Custom Search