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:

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:

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 :
Construct classes from the outside in
Use Ant for build scripts
Test using main method
Design by Contract
Choose form validation style carefully
Use a fake system clock
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -