Introduction to JUnit

Using JUnit

There is a brief introduction called the JUnit Cookbook by Kent Beck and Erich Gamma.

Here is a short recipe for writing and organizing your unit tests using JUnit.
  1. Assume that you have a Java class definition, called Q.java.
  2. Create a corresponding test class, which extends TestCase, called QTest.java in the test directory.
    1. Create a method whose name begins with the letters "test" (e.g., testIsEmpty() ) for each test.
    2. In the method, write your test.
    3. After creating a setting aka fixture for your test, you invoke 1 of the assert methods inherited from TestCase. When run, if the assert succeeds, the test passes; otherwise if fails.
      1. assertTrue
      2. assertFalse
      3. assertEquals
      4. assertNotEquals
  3. Create an AllTests.java class in the package containing this class, if none exists.
  4. The statement
    suite.addTestSuite( QTest.class );

    adds the test methods of QTest.java to the suite of TestCase objects returned by the suite method.
    Include 1 such line for each class in the package. (If I find a better way to do this, I'll get back to you.)

  5. Create an AllTests.java class for higher level packages.
  6. Finally create an AllTests.java for the project's top package level: projectname, adding a test suite for each sub-package.
  7. Compile your test code.
  8. To run your unit tests, execute
    1. java -classpath class:tool/junit.jar teamname.projectname.AllTests -g