Testing Your Java Code

It cannot be said enough that testing is the most important part of the development cycle. Even though I am not a tester (and not trying to push an agenda), I have seen that well written code without adequate test cases is not really something that any developer or team should strive for.

And in the J2EE world, the best way you could possibly test code is by using Junits.

Junit is simple testing framework designed around two key design patterns: the Command pattern and the Composite pattern. They are simple to write and check their own results and provide immediate feedback and they are relatively inexpensive to write (oh yeah – they are free in terms of cost).

A TestCase is a command object. Any class that contains test methods should subclass the TestCase class. A TestCase can define any number of public testXXX() methods. When you want to check the expected and actual test results, you invoke a variation of the assert() method.

TestCase subclasses that contain multiple testXXX() methods can use the setUp() and tearDown() methods to initialize and release any common objects under test, referred to as the test fixture. Each test runs in the context of its own fixture, calling setUp() before and tearDown() after each test method to ensure there can be no side effects among test runs.

TestCase instances can be composed into TestSuite hierarchies that automatically invoke all the testXXX() methods defined in each TestCase instance. A TestSuite is a composite of other tests, either TestCase instances or other TestSuite instances. The composite behavior exhibited by the TestSuite allows you to assemble test suites of test suites of tests, to an arbitrary depth, and run all the tests automatically and uniformly to yield a single pass or fail status.

Here is an FAQ on Junits:

http://junit.sourceforge.net/doc/faq/faq.htm

and here is an excellent introduction to Junits

http://today.java.net/pub/a/today/2004/01/22/DozenWays.html

one comment

  1. Dave says:

    *Not* free, or even particularly cheap; not at all. Tests must be maintained, refactored, etc. just like regular code, and it is, perhaps, even *more* important to keep the tests clean.

    Test ROI comes from eliminating (or at least reducing) the fear of change and the paralysis that comes with it, and the inability to make changes without being able to verify that existing behavior functions as expected.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.