Unit Testing Concepts

Before we dive into the details of testing Java code using JUnit and testing J2EE components using Cactus, let’s get acquainted with the concepts and issues underlying unit testing in general.

Units and Dependencies

The most obvious question to ask about unit testing is, “What’s a unit?” The most conservative definition of a testable “unit” is an entirely independent module of code that can be tested autonomously, separate from any other code modules. The tangible interpretation of this idealistic definition depends on the programming environment being used. In function-based programming languages, such as C, Perl, and Fortran, a unit is typically defined as a single function. Similarly, a unit in object-oriented languages like C++, Java, and C# would normally be a class.

Of course, achieving this goal of a totally independent unit of code is not entirely realistic. Virtually any code module depends on other code modules to function properly. Functional decomposition encourages algorithms to be broken down into subfunctions that are invoked by higher-order functions to solve a problem. Object-oriented design has the analogous principle of delegation of responsibilities to subordinate classes used by higher-order classes to implement particular behaviors. These common divide-and-conquer approaches to software architecture naturally lead to interdependencies among code elements.

Given this fact, achieving the goal of unit testing (i.e., verifying the valid operation ...

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.