Java Reference
In-Depth Information
Refactoring is a process that improves the design without changing its behav-
ior and is done once the tests for the new functionality pass. Examples of refactor-
ing techniques include extracting duplicated code into a method and introducing
a superclass that implements common behavior. A good way to refactor code is to
make a series of small changes and run the tests after every change. Refactoring is
an essential part of test-driven development that will help you develop a well-
designed application. For more information about refactoring, please see Fowler
[Fowler 1999].
The benefits of using JUnit
While it is certainly possible to write the tests from scratch, it's rarely a good idea.
A much better approach is to use a testing framework such as JUnit [JUnit], which
provides classes that make it easier to write and run tests. It handles exceptions
and reports test failures; provides methods for making assertions about the out-
come of calling a method; and enables you to organize tests into a hierarchy of
test suites. In addition, IDE s such as Eclipse [Eclipse] provide a GUI for running
JUnit tests. There are also various JUnit extensions that provide additional fea-
tures such as JMock, which I discuss a bit later. For more information about JUnit,
please see JUnit in Action [Massol 2003] and JUnit Recipes [Rainsberger 2004].
Simplifying and speeding up tests with mock objects
I'm a big fan of test-driven development and believe that rigorous automated test-
ing is essential if you want to successfully develop software without chaos and long
nights spent tracking down bugs. But writing tests can be difficult because of all
the setup code you must write. Moreover, if you have written a lot of tests they can
take a very long time to run, especially if they access a database. On a couple
projects that I've worked on, as more and more tests were written, it eventually
took over 30 minutes to run them. This might not sound like a long time, but it
was a big source of frustration that slowed down development because everyone
was required to run the tests prior to checking in their changes.
The main reason why a class's tests can be difficult to write and slow to execute
is because of its collaborators. Most classes are not standalone and instead collab-
orate with one or more other classes. For example, later on you will see how Place-
OrderService calls several other domain model classes, including PendingOrder ,
RestaurantRepository , and PendingOrderRepository . Collaboration is generally a
good thing because it keeps the class small. It is also essential if the class must access
external resources such as a database, because in order to do that, it must use other
classes such as those provided by JDBC . But collaboration can make testing difficult:
 
 
 
Search WWH ::




Custom Search