JUnit Overview

With this introduction to the concepts of unit testing behind us, let’s dive into the technical details of using JUnit to create and execute unit tests on basic Java code. In a later section, we’ll see how Cactus can be used to test code that must run in a J2EE container.

JUnit is a framework for writing unit tests that consists of a Java API that you use to write your tests and a set of basic tools that can be used to run your test suites and report on the results.

The JUnit API is provided as two packages: junit.framework contains the core classes that you’ll typically use to define and execute your unit tests while junit.extensions contains some potentially useful extensions to the core framework classes.

In the JUnit model, tests themselves are represented as TestCase objects. A set of related tests is organized into a TestSuite. A TestRunner actually drives a suite of tests and reports on the results. All of these classes are in the junit.framework package. The JUnit framework has several other classes and interfaces, but these are the primary ones that you’ll need to understand to get started. In keeping with the principle of simplicity we discussed earlier, the JUnit authors kept the class model in the framework as simple as possible.

The JUnit runtime model is also fairly simple. In a nutshell, executing tests using JUnit typically involves the following steps:

  1. You invoke a TestRunner on a TestSuite. Some TestRunner implementations allow you to specify an individual ...

Get Java Enterprise in a Nutshell, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.