Organizing Our Tests

About This Chapter

In the chapters concluding with Chapter 11 , Using Test Doubles, we looked at various techniques for interacting with the SUT for the purpose of verifying its behavior. In this chapter, we turn our attention to the question of how to organize the test code to make it easy to find and understand.

The basic unit of test code organization is the Test Method (page 348 ). Deciding what to put in the Test Method and where to put it is central to the topic of test organization. When we have only a few tests, how we organize them isn't terribly important. By contrast, when we have hundreds of tests, test organization becomes a critical factor in keeping our tests easy to understand and find.

This chapter begins by discussing what we should and should not include in a Test Method . Next, it explores how we can decide on which Testcase Classes (page 373 ) to put our Test Methods . Test naming depends heavily on how we have organized our tests, so we will talk about this issue next. We will then consider how to organize the Testcase Classes into test suites and where to put test code. The final topic is test code reuse—specifically, where to put reusable test code.

Basic xUnit Mechanisms

The xUnit family of Test Automation Frameworks (page 298 ) provides a number of features to help us organize our tests. The basic question, "Where do I code my tests?", is answered by putting our test code into a Test Method on a Testcase Class . We then use either Test Discovery (page 393 ) or Test Enumeration (page 399 ) to create a Test Suite Object (page 387 ) containing all the tests from the Testcase Class . The Test Runner (page 377 ) invokes a method on the Test Suite Object to run all the Test Methods .

Right-Sizing Test Methods

A test condition is something we need to prove the SUT really does; it can be described in terms of what the starting state of the SUT is, how we exercise the SUT, how we expect the SUT to respond, and what the ending state of the SUT is expected to be. A Test Method is a sequence of statements in our test scripting language that exercises one or more test conditions ( Figure 12.1 ). What should we include in a single Test Method ?

Figure 12.1. The four phases of a typical test. Each Test Method implements a Four-Phase Test (page 358 ) that ideally verifies a single test condition. Not all phases of the Four-Phase Test need be in the Test Method.

image

Many xUnit purists prefer to Verify One Condition per Test (see page 45 ) because it gives them good Defect Localization (see page 22 ). That is, when a test fails, they know exactly what is wrong in the SUT because each test verifies exactly one test condition. This is very much in contrast with manual testing, where one tends to build long, involved multiple-condition tests because of the overhead involved in setting up each test's pre-conditions. When creating xUnit-based automated tests, we have many ways of dealing with this frequently repeated fixture setup (as described in Chapter 8 , Transient Fixture Management ), so we tend to Verify One Condition per Test . We call a test that verifies too many test conditions an Eager Test (see Assertion Roulette on page 224 ) and consider it a code smell.

A test that verifies a single test condition executes a single code path through the SUT and it should execute exactly the same path each time it runs; that is what makes it a Repeatable Test (see page 26 ). Yes, that means we need as many test methods as we have paths through the code—but how else can we expect to achieve full code coverage? What makes this pattern manageable is that we Isolate the SUT (see page 43 ) when we write unit tests for each class so we only have to focus on paths through a single object. Also, because each test should verify only a single path through the code, each test method should consist of strictly sequential statements that describe what should happen on that one path. 1 Another reason we Verify One Condition per Test (see page 45 ) is to Minimize Test Overlap (see page 44 ) so that we have fewer tests to modify if we later modify the behavior of the SUT.

Brian Marrick has developed an interesting compromise that I call "While We're at It," 2 which leverages the test fixture we already have set up to run some additional checks and assertions. Marrick clearly marks these elements with comments to indicate that if changes to the SUT obsolete that part of the test, they can be easily deleted. This strategy minimizes the effort needed to maintain the extra test code.

Test Methods and Testcase Classes

A Test Method needs to live on a Testcase Class . Should we put all our Test Methods onto a single Testcase Class for the application? Or should we create a Testcase Class for each Test Method ? Of course, the right answer lies somewhere between these two extremes, and it will change over the life of our project.

Testcase Class per Class

When we write our first few Test Methods , we can put them all onto a single Testcase Class . As the number of Test Methods increases, we will likely want to split the Testcase Class so that one Testcase Class per Class (page 617 ) is tested, which reduces the number of Test Methods per class ( Figure 12.2 ). As those Testcase Classes get too big, we usually split the classes further. In that case, we need to decide which Test Methods to include in each Testcase Class .

Figure 12.2. A production class with a single Testcase Class. With the Testcase Class per Class pattern, a single Testcase Class holds all the Test Methods for all the behavior of our SUT class. Each Test Method may need to create a different fixture either in-line or by delegating that task to a Creation Method (page 415 ).

image

Testcase Class per Feature

One school of thought is to put all Test Methods that verify a particular feature of the SUT—where a "feature" is defined as one or more methods and attributes that collectively implement some capability of the SUT—into a single Testcase Class ( Figure 12.3 ). This makes it easy to see all test conditions for that feature. (Use of appropriate Test Naming Conventions helps achieve this clarity.) It can, however, result in similar fixture setup code being required in each Testcase Class .

Figure 12.3. A production class with one Testcase Class for each feature. With the Testcase Class per Feature pattern, we have one Testcase Class for each major capability or feature supported by our SUT class. The Test Methods on that test class exercise various aspects of that feature after building whatever test fixture they require.

image

Testcase Class per Fixture

The opposing view is that one should group all Test Methods that require the same test fixture (same pre-conditions) into one Testcase Class per Fixture (page 631 ; see Figure 12.4 ). This facilitates putting the test fixture setup code into the setUp method ( Implicit Setup ; see page 424 ) but can result in scattering of the test conditions for each feature across many Testcase Classes .

Figure 12.4. A production class with one Testcase Class for each fixture. With the Testcase Class per Fixture pattern, we have one Testcase Class for each possible test fixture (test pre-condition) of our SUT class. The Test Methods on that test class exercise various features from the common starting point.

image

Choosing a Test Method Organization Strategy

Clearly, there is no single "best practice" we can always follow; the best practice is the one that is most appropriate for the particular circumstance. Testcase Class per Fixture is commonly used when we are writing unit tests for stateful objects and each method needs to be tested in each state of the object. Testcase Class per Feature (page 624 ) is more appropriate when we are writing customer tests against a Service Facade [CJ2EEP] ; it enables us to keep all the tests for a customer-recognizable feature together. This pattern is also more commonly used when we rely on a Prebuilt Fixture (page 429 ) because fixture setup logic is not required in each test. When each test needs a slightly different fixture, the right answer may be to select the Testcase Class per Feature pattern and use a Delegated Setup (page 411 ) to facilitate setting up the fixtures.

Test Naming Conventions

The names we give to our Testcase Classes and Test Methods are crucial in making our tests easy to find and understand. We can make the test coverage more obvious by naming each Test Method systematically based on which test condition it verifies. Regardless of which test method organization scheme we use, we would like the combination of the names of the test package, the Testcase Class, and the Test Method to convey at least the following information:

  • The name of the SUT class
  • The name of the method or feature being exercised
  • The important characteristics of any input values related to the exercising of the SUT
  • Anything relevant about the state of the SUT or its dependencies

These items are the "input" part of the test condition. Obviously, this is a lot to communicate in just two names but the reward is high if we can achieve it: We can tell exactly what test conditions we have tests for merely by looking at the names of the classes and methods in an outline view of our IDE. Figure 12.5 provides an example.

Figure 12.5. A production class with one Testcase Class for each test fixture. When we use the Testcase Class per Fixture pattern, the class name can describe the fixture, leaving the method name available for describing the inputs and expected outputs.

image

Figure 12.5 also shows how useful it is to include the "expectations" side of the test condition:

  • The outputs (responses) expected when exercising the SUT
  • The expected post-exercise state of the SUT and its dependencies

This information can be included in the name of the Test Method prefixed by "should." If this nomenclature makes the names too long, 3 we can always access the expected outcome by looking at the body of the Test Method .

Organizing Test Suites

The Testcase Class acts as a Test Suite Factory (see Test Enumeration ) when it returns a Test Suite Object containing a collection of Testcase Objects (page 382 ), each representing a Test Method ( Figure 12.6 ). This is the default organization mechanism provided by xUnit. Most Test Runners allow any class to act as a Test Suite Factory by implementing a Factory Method [GOF] , which is typically called suite .

Figure 12.6. A Testcase Class acting as a Test Suite Factory. By default, the Testcase Class acts as a Test Suite Factory to produce the Test Suite Object that the Test Runner requires to execute our tests. We can also enumerate a specific set of tests we want to run by providing a Test Suite Factory that returns a Test Suite Object containing only the desired tests.

image

Running Groups of Tests

We often want to run groups of tests (i.e., a test suite) but we don't want this decision to constrain how we organize them. A popular convention is to create a special Test Suite Factory called AllTests for each package of tests. We don't need to stop there, however: We can create Named Test Suites (page 592 ) for any collection of tests we want to run together. A good example is a Subset Suite (see Named Test Suite ) that allows us to run just those tests that need software deployed to the Web server (or not deployed to the Web server!). We usually have at least a Subset Suite for all the unit tests and another Subset Suite for just the customer tests (they often take a long time to execute). Some variants of xUnit support Test Selection (page 403 ), which we can use instead of defining Subset Suites .

Such runtime groupings of tests often reflect the environment in which they need to run. For example, we might have one Subset Suite that includes all tests that can be run without the database and another Subset Suite that includes all tests that depend on the database. Likewise, we might have separate Subset Suites for tests that do, and do not, rely on the Web server. If our test package includes these various kinds of test suites, we can define AllTests as a Suite of Suites (see Test Suite Object ) composed of these Subset Suites . Then any test that is added to one of the Subset Suites will also be run in AllTests without incurring extra test maintenance effort.

Running a Single Test

Suppose a Test Method fails in our Testcase Class. We decide to put a breakpoint on a particular method—but that method is called in every test. Our first reaction might be to just muddle through by clicking "Go" each time the breakpoint is hit until we are being called from the test of interest. One possibility is to disable (by commenting out) the other Test Methods so they are not run. Another option is to rename the other Test Methods so that the xUnit Test Discovery mechanism will not recognize them as tests. In variants of xUnit that use method attributes or annotations, we can add the "Ignore" attribute to a test method instead. Each of these approaches introduces the potential problem of a Lost Test (see Production Bugs on page 268 ) , although the "Ignore" approach does remind us that some tests are being ignored. In members of the xUnit family that provide a Test Tree Explorer (see Test Runner ), we can simply select a single test to be run from the hierarchy view of the test suite, as shown in Figure 12.7 .

Figure 12.7. A Test Tree Explorer showing the structure of the tests in our suite. We can use the Test Tree Explorer to drill down into the runtime structure of the test suite and run individual tests or subsuites.

image

When none of these options is available, we can use a Test Suite Factory to run a single test. Wait a minute! Aren't test suites all about running groups of tests that live in different Testcase Classes ? Well, yes, but that doesn't mean we can't use them for other purposes. We can define a Single Test Suite 4 (see Named Test Suite ) that runs a particular test. To do so, we call the constructor of the Testcase Class with the specific Test Method's name as an argument.

Test Code Reuse

Test Code Duplication (page 213 ) can significantly increase the cost of writing and maintaining tests. Luckily, a number of techniques for reusing test logic are available to us. The most important consideration is that any reuse not compromise the value of the Tests as Documentation (see page 23 ). I don't recommend reuse of the actual Test Method in different circumstances (e.g., with different fixtures), as this kind of reuse is typically a sign of a Flexible Test (see Conditional Test Logic on page 200 ) that tests different things in different circumstances. Most test code reuse is achieved either through Implicit Setup or Test Utility Methods (page 599 ). The major exception is the reuse of Test Doubles (page 522 ) by many tests; we can treat these Test Double classes as a special kind of Test Helper (page 643 ) when thinking about where to put them.

Test Utility Method Locations

Many variants of xUnit provide a special Testcase Superclass (page 638 )—typically called "TestCase"—from which all Testcase Classes should (and, in some cases, must) inherit either directly or indirectly ( Figure 12.8 ). If we have useful utility methods on our Testcase Class that we want to reuse in other Testcase Classes , we may find it helpful to create one or more Testcase Superclasses from which to inherit instead of "TestCase." If we take this step, we need to be careful if those methods need to see types or classes that reside in various packages within the SUT—our root Testcase Superclass should not depend on those types or classes directly, as that is likely to result in a cyclical dependency graph. We may be able to create a Testcase Superclass for each test package to keep our test class dependencies noncyclic. The alternative is to create a Test Helper for each domain package and put the various Test Helpers in the appropriate test packages. This way, a Testcase Class is not forced to choose a single Testcase Superclass ; it can merely "use" the appropriate Test Helpers .

Figure 12.8. The various places we can put Test Utility Methods. The primary decision-making criterion is the desired scope of reusability of the Test Methods.

image

TestCase Inheritance and Reuse

The most commonly used reason for inheriting methods from a Testcase Superclass is to access Test Utility Methods . Another use is when testing frameworks and their plug-ins; it can be useful to create a conformance test that specifies the general behavior of the plug-in via a Template Method [GOF] that calls methods provided by a subclass specific to the kind of plug-in being tested to check specific details of the plug-in. This scenario is rare enough that I won't describe it further here; please refer to [FaT] for a more complete description.

Test File Organization

Now we face a new question: Where should we put our Testcase Classes ? Obviously, these classes should be stored in the source code repository [SCM] along with the production code. Beyond that criterion, we have quite a range of choices. The test packaging strategy we choose will very much depend on our environment—many IDEs include constraints that make certain strategies unworkable. The key issue is to Keep Test Logic Out of Production Code (see page 45 ) and yet to be able to find the corresponding test for each piece of code or functionality.

Built-in Self-Test

With a built-in self-test , the tests are included with the production code and can be run at any time. No provision is made for keeping them separate. Many organizations want to Keep Test Logic Out of Production Code so built-in self-tests may not be a good option for them. This consideration is particularly important in memory-constrained environments where we don't want test code taking up valuable space.

Some development environments encourage us to keep the tests and the production code together. For example, SAP's ABAP Unit supports the keyword "For Testing," which tells the system to disable the tests when the code is transported into the production environment.

Test Packages

If we decide to put the Testcase Classes into separate test packages, we can organize them in several ways. We can keep the tests separate by putting them into one or more test packages while keeping them in the same source tree, or we can put the tests into the same logical package but physically store them in a parallel source tree. The latter approach is frequently used in Java because it avoids the problem of tests not being able to see "package-protected" methods on the SUT. 5 Some IDEs may reject using this approach by insisting that a package be wholly contained within a single folder or project. When we use test packages under each production code package, we may need to use a build-time test stripper to exclude them from production builds.

Test Dependencies

However we decide to store and manage the source code, we need to ensure that we eliminate any Test Dependency in Production (see Test Logic in Production on page 217 ) because even a test stripper cannot remove the tests if production code needs them to be present to run. This requirement makes paying attention to our class dependencies important. We also don't want to have any Test Logic in Production because it means we aren't testing the same code that we will eventually run in production. This issue is discussed in more detail in Chapter 6 , Test Automation Strategy .

What's Next?

Now that we've looked at how to organize our test code, we should become familiar with a few more testing patterns. These patterns are introduced in Chapter 13 , Testing with Databases .