Use a testing framework (JUnit)
Use a testing framework to ensure your class fulfills its contract.
One widely used framework is JUnit.
JUnit has these advantages:
- it's simple to use
- it can test a single class at a time, or a suite of tests can be created
for a group of classes
- it greatly increases your confidence in the correctness of your code
- it often improves the design of the class you are testing - since you spend
more time thinking about how an object is actually
used, instead of its implementation, defects in its interface
become more obvious
- failure of a test is glaringly obvious
- the positive feedback provided by successful tests produces unmistakably
warm, fuzzy feelings even in the embittered heart of an experienced programmer ;)
Test Doubles
Unit testing is about testing classes in isolation, one at a time.
However, classes usually don't operate in isolation - they usually have collaborators, other
classes needed for correct operation.
In some cases, those collaborators aren't immediately available during unit testing.
For example, in a servlet application, the underlying request and response objects are created by the
servlet container, and passed to the application for further processing.
During unit testing, the 'real' request and response are not typically available, since the servlet
container isn't running.
Thus, test doubles are often required during unit testing.
Test doubles are used to mimic the collaborators of a class being tested.
See xUnitPatterns.com by Gerard
Meszaros for more information.
Tests and Packages
Some programmers put their unit tests in a package separate from the classes being tested.
This is neither necessary nor desirable.
It's not necessary since the tests can always be placed in the same package as the items being tested.
It's not desirable for two reasons:
- it's not compatible with package-by-feature
- it often forces you to increase the scope of items being tested to
public
, merely for the sake of running unit tests
From Effective Java, by Johsua Bloch:
"It is not acceptable to make a class, interface, or member a part of a package's exported API to facilitate testing.
Luckily, it isn't necessary either, as tests can be made to run as part of the package being tested, thus gaining access to its package-private elements."
See Also :