xUnit Basics Patterns
Patterns in This Chapter
Test Definition
Test Method 348
Four-Phase Test 358
Assertion Method 362
Assertion Message 370
Testcase Class 373
Test Execution
Test Runner 377
Testcase Object 382
Test Suite Object 387
Test Discovery 393
Test Enumeration 399
Test Selection 403
Test Method
Where do we put our test code?
We encode each test as a single Test Method on some class.
Fully Automated Tests (see page 26 ) consist of test logic. That logic has to live somewhere before we can compile and execute it.
How It Works
We define each test as a method, procedure, or function that implements the four phases (see Four-Phase Test on page 358 ) necessary to realize a Fully Automated Test . Most notably, the Test Method must include assertions if it is to be a Self-Checking Test (see page 26 ).
We organize the test logic following one of the standard Test Method templates to make the type of test easily recognizable by test readers. In a Simple Success Test, we have a purely linear flow of control from fixture setup through exercising the SUT to result verification. In an Expected Exception Test, language-based structures direct us to error-handling code. If we reach that code, we pass the test; if we don't, we fail it. In a Constructor Test, we simply instantiate an object and make assertions against its attributes.
Why We Do This
We have to encode the test logic somewhere. In the procedural world, we would encode each test as a test case procedure located in a file or module. In object-oriented programming languages, the preferred option is to encode them as methods on a suitable Testcase Class (page 373 ) and then to turn these Test Methods into Testcase Objects (page 382 ) at runtime using either Test Discovery (page 393 ) or Test Enumeration (page 399 ).
We follow the standard test templates to keep our Test Methods as simple as possible. This greatly increases their utility as system documentation (see page 23 ) by making it easier to find the description of the basic behavior of the SUT. It is a lot easier to recognize which tests describe this basic behavior if only Expected Exception Tests contain error-handling language constructs such as try/catch .
Implementation Notes
We still need a way to run all the Test Methods tests on the Testcase Class . One solution is to define a static method on the Testcase Class that calls each of the test methods. Of course, we would also have to deal with counting the tests and determining how many passed and how many failed. Because this functionality is needed for a test suite anyway, a simple solution is to instantiate a Test Suite Object (page 387 ) to hold each Test Method . 1 This approach is easy to implement if we create an instance of the Testcase Class for each Test Method using either Test Discovery or Test Enumeration .
In statically typed languages such as Java and C#, we may have to include a throws clause as part of the Test Method declaration so the compiler won't complain about the fact that we are not handling the checked exceptions that the SUT has declared it may throw. In effect, we tell the compiler that "The Test Runner (page 377 ) will deal with the exceptions."
Of course, different kinds of functionality need different kinds of Test Methods. Nevertheless, almost all tests can be boiled down to one of three basic types.
Variation: Simple Success Test
Most software has an obvious success scenario (or "happy path"). A Simple Success Test verifies the success scenario in a simple and easily recognized way. We create an instance of the SUT and call the method(s) that we want to test. We then assert that the expected outcome has occurred. In other words, we follow the normal steps of a Four-Phase Test . What we don't do is catch any exceptions that could happen. Instead, we let the Test Automation Framework (page 298 ) catch and report them. Doing otherwise would result in Obscure Tests (page 186 ) and would mislead the test reader by making it appear as if exceptions were expected. See Tests as Documentation for the rationale behind this approach.
Another benefit of avoiding try/catch -style code is that when errors do occur, it is a lot easier to track them down because the Test Automation Framework reports the location where the actual error occurred deep in the SUT rather than the place in our test where we called an Assertion Method (page 362 ) such as fail or assertTrue . These kinds of errors turn out to be much easier to troubleshoot than assertion failures.
Variation: Expected Exception Test
Writing software that passes the Simple Success Test is pretty straightforward. Most of the defects in software appear in the various alternative paths—especially the ones that relate to error scenarios, because these scenarios are often Untested Requirements (see Production Bugs on page 268 ) or Untested Code (see Production Bugs ). An Expected Exception Test helps us verify that the error scenarios have been coded correctly. We set up the test fixture and exercise the SUT in each way that should result in an error. We ensure that the expected error has occurred by using whatever language construct we have available to catch the error. If the error is raised, flow will pass to the error-handling block. This diversion may be enough to let the test pass, but if the type or message contents of the exception or error is important (such as when the error message will be shown to a user), we can use an Equality Assertion (see Assertion Method ) to verify it. If the error is not raised, we call fail to report that the SUT failed to raise an error as expected.
We should write an Expected Exception Test for each kind of exception that the SUT is expected to raise. It may raise the error because the client (i.e., our test) has asked it to do something invalid, or it may translate or pass through an error raised by some other component it uses. We should not write an Expected Exception Test for exceptions that the SUT might raise but that we cannot force to occur on cue, because these kinds of errors should show up as test failures in the Simple Success Tests . If we want to verify that these kinds of errors are handled properly, we must find a way to force them to occur. The most common way to do so is to use a Test Stub (page 529 ) to control the indirect input of the SUT and raise the appropriate errors in the Test Stub .
Exception tests are very interesting to write about because of the different ways the xUnit frameworks express them. JUnit 3.x provides a special Expected-Exception class to inherit from. This class forces us to create a Testcase Class for each Test Method (page 348 ), however, so it really doesn't save any effort over coding a try/catch block and does result in a large number of very small Testcase Classes . Later versions of JUnit and NUnit (for .NET) provide a special ExpectedException method attribute (called an annotation in Java) to tell the Test Automation Framework to fail the test if that exception isn't raised. This method attribute allows us to include message text if we want to specify exactly which text to expect in addition to the type of the exception.
Languages that support blocks, such as Smalltalk and Ruby, can provide special assertions to which we pass the block of code to be executed as well as the expected exception/error object. The Assertion Method implements the error-handling logic required to determine whether the error has, in fact, occurred. This makes our Test Methods much simpler, even though we may need to examine the names of the assertions more closely to see which type of test we have.
Variation: Constructor Test
We would have a lot of Test Code Duplication (page 213 ) if every test we wrote had to verify that the objects it creates in its fixture setup phase are correctly instantiated. We avoid this step by testing the constructor(s) separately from other Test Methods whenever the constructor contains anything more complex than a simple field assignment from the constructor parameters. These Constructor Tests provide better Defect Localization (see page 22 ) than including constructor logic verification in other tests. We may need to write one or more tests for each constructor signature. Most Constructor Test s will follow a Simple Success Test template; however, we can use an Expected Exception Test to verify that the constructor correctly reports invalid arguments by raising an exception.
We should verify each attribute of the object or data structure regardless of whether we expect it to be initialized. For attributes that should be initialized, we can use an Equality Assertion to specify the correct value. For attributes that should not be initialized, we can use a Stated Outcome Assertion (see Assertion Method ) appropriate to the type of the attribute [e.g., assertNull(anObjectReference) for object variables or pointers]. Note that if we are organizing our tests with one Testcase Class per Fixture (page 631 ), we can put each assertion into a separate Test Method to give optimal Defect Localization .
Variation: Dependency Initialization Test
When we have an object with a substitutable dependency, we need to make sure that the attribute that holds the reference to the depended-on component (DOC) is initialized to the real DOC when the software is run in production. A Dependency Initialization Test is a Constructor Test that asserts that this attribute is initialized correctly. It is often done in a different Test Method from the normal Constructor Tests to improve its visibility.
Example: Simple Success Test
The following example illustrates a test where the novice test automater has included code to catch exceptions that he or she knows might occur (or that the test automater might have encountered while debugging the code).
public void testFlightMileage_asKm() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
try {
// exercise SUT
newFlight.setMileage(1122);
// verify results
int actualKilometres = newFlight.getMileageAsKm();
int expectedKilometres = 1810;
// verify results
assertEquals( expectedKilometres, actualKilometres);
} catch (InvalidArgumentException e) {
fail(e.getMessage());
} catch (ArrayStoreException e) {
fail(e.getMessage());
}
}
The majority of the code is unnecessary and just obscures the intent of the test. Luckily for us, all of this exception handling can be avoided. xUnit has built-in support for catching unexpected exceptions. We can rip out all the exception-handling code and let the Test Automation Framework catch any unexpected exception that might be thrown. Unexpected exceptions are counted as test errors because the test terminates in a way we didn't anticipate. This is useful information and is not considered to be any more severe than a test failure.
public void testFlightMileage_asKm() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
newFlight.setMileage(1122);
// exercise mileage translator
int actualKilometres = newFlight.getMileageAsKm();
// verify results
int expectedKilometres = 1810;
assertEquals( expectedKilometres, actualKilometres);
}
This example is in Java (a statically typed language), so we had to declare that the SUT may throw an exception as part of the Test Method signature.
Example: Expected Exception Test Using try/catch
The following example is a partially complete test to verify an exception case. The novice test automater has set up the right test condition to cause the SUT to raise an error.
public void testSetMileage_invalidInput() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
// exercise SUT
newFlight.setMileage(-1122); // invalid
// how do we verify an exception was thrown?
}
Because the Test Automation Framework will catch the exception and fail the test, the Test Runner will not exhibit the green bar even though the SUT's behavior is correct. We can introduce an error-handling block around the exercise phase of the test and use it to invert the pass/fail criteria (pass when the exception is thrown; fail when it is not). Here's how to verify that the SUT fails as expected in JUnit 3.x:
public void testSetMileage_invalidInput() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
try {
// exercise SUT
newFlight.setMileage(-1122);
fail("Should have thrown InvalidInputException");
} catch( InvalidArgumentException e) {
// verify results
assertEquals( "Flight mileage must be positive",
e.getMessage());
}
}
This style of try/catch can be used only in languages that allow us to specify exactly which exception to catch. It won't work if we want to catch a generic exception or the same exception that the Assertion Method fail throws, because these exceptions will send us into the catch clause. In these cases we need to use the same style of Expected Exception Test as used in tests of Custom Assertions (page 474 ).
public void testSetMileage_invalidInput2() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
try {
// exercise SUT
newFlight.setMileage(-1122);
// cannot fail() here if SUT throws same kind of exception
} catch( AssertionFailedError e) {
// verify results
assertEquals( "Flight mileage must be positive",
e.getMessage());
return;
}
fail("Should have thrown InvalidInputException");
}
Example: Expected Exception Test Using Method Attributes
NUnit provides a method attribute that lets us write an Expected Exception Test without forcing us to code a try/catch block explicitly.
[Test]
[ExpectedException(typeof( InvalidArgumentException),
"Flight mileage must be > zero")]
public void testSetMileage_invalidInput_AttributeWithMessage()
{
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
// exercise SUT
newFlight.setMileage(-1122);
}
This approach does make the test much more compact but doesn't provide a way to specify anything but the type of the exception or the message it contains. If we want to make any assertions on other contents of the exception (to avoid Sensitive Equality ; see Fragile Test on page 239 ), we'll need to use try/catch .
Example: Expected Exception Test Using Block Closure
Smalltalk's SUnit provides another mechanism to achieve the same thing:
testSetMileageWithInvalidInput
self
should: [Flight new mileage: -1122]
raise: RuntimeError new 'Should have raised error'
Because Smalltalk supports block closures, we pass the block of code to be executed to the method should:raise: along with the expected Exception object. Ruby's Test::Unit uses the same approach:
def testSetMileage_invalidInput
flight = Flight.new();
assert_raises( RuntimeError, "Should have raised error") do
flight.setMileage(-1122)
end
end
The code between the do/end pair is a closure that is executed by the assert_raises method. If it doesn't raise an instance of the first argument (the class RuntimeError ), the test fails and presents the error message supplied.
Example: Constructor Test
In this example, we need to build a flight to test the conversion of the flight distance from miles to kilometers. First, we'll make sure the flight is constructed properly.
public void testFlightMileage_asKm2() throws Exception {
// set up fixture
// exercise constructor
Flight newFlight = new Flight(validFlightNumber);
// verify constructed object
assertEquals(validFlightNumber, newFlight.number);
assertEquals("", newFlight.airlineCode);
assertNull(newFlight.airline);
// set up mileage
newFlight.setMileage(1122);
// exercise mileage translator
int actualKilometres = newFlight.getMileageAsKm();
// verify results
int expectedKilometres = 1810;
assertEquals( expectedKilometres, actualKilometres);
// now try it with a canceled flight
newFlight.cancel();
try {
newFlight.getMileageAsKm();
fail("Expected exception");
} catch (InvalidRequestException e) {
assertEquals( "Cannot get cancelled flight mileage",
e.getMessage());
}
}
This test is not a Single-Condition Test (see page 45 ) because it examines both object construction and distance conversion behavior. If object construction fails, we won't know which issue was the cause of the failure until we start debugging the test.
It would be better to separate this Eager Test (see Assertion Roulette on page 224 ) into two tests, each of which is a Single-Condition Test . This is most easily done by cloning the Test Method , renaming each copy to reflect what it would do if it were a Single-Condition Test , and then removing any code that doesn't satisfy that goal.
Here's an example of a simple Constructor Test :
public void testFlightConstructor_OK() throws Exception {
// set up fixture
// exercise SUT
Flight newFlight = new Flight(validFlightNumber);
// verify results
assertEquals( validFlightNumber, newFlight.number );
assertEquals( "", newFlight.airlineCode );
assertNull( newFlight.airline );
}
While we are at it, we might as well specify what should occur if an invalid argument is passed to the constructor by using the Expected Exception Test template for our Constructor Test :
public void testFlightConstructor_badInput() {
// set up fixture
BigDecimal invalidFlightNumber = new BigDecimal(-1023);
// exercise SUT
try {
Flight newFlight = new Flight(invalidFlightNumber);
fail("Didn't catch negative flight number!");
} catch (InvalidArgumentException e) {
// verify results
assertEquals( "Flight numbers must be positive",
e.getMessage());
}
}
Now that we know that our constructor logic is well tested, we are ready to write our Simple Success Test for our mileage translation functionality. Note how much simpler it has become because we can focus on verifying the business logic:
public void testFlightMileage_asKm() throws Exception {
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
newFlight.setMileage(1122);
// exercise mileage translator
int actualKilometres = newFlight.getMileageAsKm();
// verify results
int expectedKilometres = 1810;
assertEquals( expectedKilometres, actualKilometres);
}
So what happens if the constructor logic is defective? This test will likely fail because its output depends on the value passed to the constructor. The constructor test will also fail. That failure will tell us to look at the constructor logic first. Once that problem is fixed, this test will likely pass. If it doesn't, then we can focus on fixing the getMileageAsKm method logic. This is a good example of Defect Localization .
Four-Phase Test
How do we structure our test logic to make what we are testing obvious?
We structure each test with four distinct parts executed in sequence.
How It Works
We design each test to have four distinct phases that are executed in sequence: fixture setup, exercise SUT, result verification, and fixture teardown.
- In the first phase, we set up the test fixture (the "before" picture) that is required for the SUT to exhibit the expected behavior as well as anything you need to put in place to be able to observe the actual outcome (such as using a Test Double ; see page 522 ).
- In the second phase, we interact with the SUT.
- In the third phase, we do whatever is necessary to determine whether the expected outcome has been obtained.
- In the fourth phase, we tear down the test fixture to put the world back into the state in which we found it.
Why We Do This
The test reader must be able to quickly determine what behavior the test is verifying. It can be very confusing when various behaviors of the SUT are being invoked—some to set up the pre-test state (fixture) of the SUT, others to exercise the SUT, and yet others to verify the post-test state of the SUT. Clearly identifying the four phases makes the intent of the test much easier to see.
The fixture setup phase of the test establishes the SUT's state prior to the test, which is an important input to the test. The exercise SUT phase is where we actually run the software we are testing. When reading the test, we need to see which software is being run. The result verification phase of the test is where we specify the expected outcome. The final phase, fixture teardown, is all about housekeeping. We wouldn't want to obscure the important test logic with it because it is completely irrelevant from the perspective of Tests as Documentation (see page 23 ).
We should avoid the temptation to test as much functionality as possible in a single Test Method (page 348 ) because that can result in Obscure Tests (page 186 ). In fact, it is preferable to have many small Single-Condition Tests (see page 45 ). Using comments to mark the phases of a Four-Phase Test is a good source of self-discipline, in that it makes it very obvious when our tests are not Single-Condition Tests . It will be self-evident if we have multiple exercise SUT phases separated by result verification phases or if we have interspersed fixture setup and exercise SUT phases. Sure, the tests may work—but they will provide less Defect Localization (see page 22 ) than if we have a bunch of independent Single-Condition Tests .
Implementation Notes
We have several options for implementing the Four-Phase Test . In the simplest case, each test is completely free-standing. All four phases of the test are contained within the body of the Test Method . This structure implies we are using In-line Setup (page 408 ) and either Garbage-Collected Teardown (page 500 ) or In-line Teardown (page 509 ). It is the most appropriate choice when we are using Testcase Class per Class (page 617 ) or Testcase Class per Feature (page 624 ) to organize our Test Methods .
The other choice is to take advantage of the Test Automation Framework's (page 298 ) support for Implicit Setup (page 424 ) and Implicit Teardown (page 516 ). We factor out the common fixture setup and fixture teardown logic into setUp and tearDown methods on the Testcase Class (page 373 ). This leaves only the exercise SUT and result verification phases in the Test Method . This approach is an appropriate choice when we are using Testcase Class per Fixture (page 631 ). We can also use this approach to set up common parts of the fixture when using Testcase Class per Class (page 617 ) or Testcase Class per Feature or to tear down the fixture when using Automated Teardown (page 503 ).
Example: Four-Phase Test (In-line)
Here is an example of a test that is clearly a Four-Phase Test :
public void testGetFlightsByOriginAirport_NoFlights_inline()
throws Exception {
// Fixture setup
NonTxFlightMngtFacade facade =new NonTxFlightMngtFacade();
BigDecimal airportId = facade.createTestAirport("1OF");
try {
// Exercise system
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(airportId);
// Verify outcome
assertEquals( 0, flightsAtDestination1.size() );
} finally {
// Fixture teardown
facade.removeAirport( airportId );
}
}
All four phases of the Four-Phase Test are included as in-line code. Because the calls to Assertion Methods (page 362 ) raise exceptions, we need to surround the fixture teardown part of the Test Method with a try/finally construct to ensure that it is run in all cases.
Example: Four-Phase Test (Implicit Setup/Teardown)
Here is the same Four-Phase Test with the fixture setup and fixture teardown logic moved out of the Test Method :
NonTxFlightMngtFacade facade = new NonTxFlightMngtFacade();
private BigDecimal airportId;
protected void setUp() throws Exception {
// Fixture setup
super.setUp();
airportId = facade.createTestAirport("1OF");
}
public void testGetFlightsByOriginAirport_NoFlights_implicit()
throws Exception {
// Exercise SUT
List flightsAtDestination1 =
facade.getFlightsByOriginAirport(airportId);
// Verify outcome
assertEquals( 0, flightsAtDestination1.size() );
}
protected void tearDown() throws Exception {
// Fixture teardown
facade.removeAirport(airportId);
super.tearDown();
}
Because the tearDown method is called automatically even after test failures, we don't need the try/finally construct inside the Test Method . The downside, however, is that references to our fixture must be held in instance variables rather than local variables.
Assertion Method
How do we make tests self-checking?
We call a utility method to evaluate whether an expected outcome has been achieved.
A key part of writing Fully Automated Tests (see page 26 ) is to make them Self-Checking Tests (see page 26 ) to avoid having to inspect the outcome of each test for correctness each time it is run. This strategy involves finding a way to express the expected outcome so that it can be verified automatically by the test itself.
Assertion Methods give us a way to express the expected outcome in a way that is both executable by the computer and useful to the human reader, who can then use the Tests as Documentation (see page 23 ).
How It Works
We encode the expected outcome of the test as a series of assertions that state what should be true for the test to pass. The assertions are realized as calls to Assertion Methods that encapsulate the mechanism that causes the test to fail. The Assertion Methods may be provided by the Test Automation Framework (page 298 ) or by the test automater as Custom Assertions (page 474 ).
Why We Do This
Encoding the expected outcome using Conditional Test Logic (page 200 ) is very verbose and makes tests hard to read and understand. It is also much more likely to lead to Test Code Duplication (page 213 ) and Buggy Tests (page 260 ). Assertion Methods help us avoid these issues by moving that complexity into reusable Test Utility Methods (page 599 ); these methods can then be verified as working correctly using Test Utility Tests (see Test Utility Method ).
Implementation Notes
Although all members of the xUnit family provide Assertion Methods, they do so with a fair degree of variability. The key implementation considerations are as follows:
- How to call the Assertion Methods
- How to choose the best Assertion Method to call
- What information to include in the Assertion Message (page 370 )
Calling Built-in Assertion Methods
The way the Assertion Methods are called from within the Test Method (page 348 ) varies from language to language and from framework to framework. The language features determine what is possible and preferable, while the framework builders chose which options to use. The names these developers chose for the Assertion Methods were influenced by how they chose to access them. Here are the most common options for accessing the Assertion Methods :
-
The Assertion Methods are inherited from a Testcase Superclass (page 638 ) provided by the framework. Such methods may be invoked as though they were provided locally on the Testcase Class (page 373 ). The original version of Java's JUnit, for example, used this approach by providing a Testcase Superclass that inherits from the class
Assert, which contains the actual Assertion Methods . -
The Assertion Methods are provided via a globally accessible class or module. They are invoked using the class or module name to fully qualify the Assertion Method name. NUnit, for example, uses this approach [e.g.,
Assert.isTrue(x);]. JUnit does allow assertions to be invoked as static methods on theAssertclass [e.g.,Assert.assertTrue(x)] but this is not usually necessary because they are inherited via the Testcase Superclass . -
The Assertion Methods are provided as "mix-ins" or macros. Ruby's Test::Unit, for example, provides the Assertion Methods in a module called
Assertthat can be included in any class, 2 thereby allowing the Assertion Methods to be used as though defined within the Testcase Class [e.g.,assert_equal(a,b)]. CppUnit, by contrast, defines the Assertion Methods as macros, which are expanded before the compiler sees the code.
Assertion Messages
Assertion Methods typically take an optional Assertion Message as a text parameter that is included in the output when the assertion fails. This structure allows the test automater to explain to the test maintainer exactly which Assertion Method failed and to better explain what should have occurred. The error detected by the test will be much easier to debug if the Assertion Method provides more information about why it failed. Choosing the right Assertion Method goes a long way toward achieving this goal because many of the built-in Assertion Methods provide useful diagnostic information about the values of the arguments. This is especially true for Equality Assertions .
One of the biggest differences between members of the xUnit family is where the optional Assertion Message appears in the argument list. Most members tack it on to the end as an optional argument. JUnit, however, makes the Assertion Message the first argument when it is present.
Choosing the Right Assertion
We have two goals for the calls to Assertion Methods in our Test Methods :
- Fail the test when something other than the expected outcome occurs
- Document how the SUT is supposed to behave (i.e., Tests as Documentation )
To achieve these goals we must strive to use the most appropriate Assertion Method . While the syntax and naming conventions vary from one member of the xUnit family to the next, most provide a basic set of assertions that fall into the following categories:
-
Single-Outcome Assertions such as
fail; these take no arguments because they always behave the same way. -
Stated Outcome Assertions such as
assertNotNull(anObjectReference)andassertTrue(aBooleanExpression); these compare a single argument to an outcome implied by the method name. -
Expected Exception Assertions such as
assert_raises(expectedError) { codeToExecute };these evaluate a block of code and a single expected exception argument. -
Equality Assertions such as
assertEqual(expected, actual); these compare two objects or values for equality. -
Fuzzy Equality Assertions such as
assertEqual(expected, actual, tolerance); these determine whether two values are "close enough" to each other by using a "tolerance" or "comparison mask."
Variation: Equality Assertion
Equality Assertions are the most common examples of Assertion Methods . They are used to compare the actual outcome with an expected outcome that is expressed in the form of a constant Literal Value (page 714 ) or an Expected Object (see State Verification on page 462 ) . By convention, the expected value is specified first and the actual value follows it. The diagnostic message that is generated by the Test Automation Framework makes sense only when they are provided in this order. The equality of the two objects is usually determined by invoking the equals method on the expected object. If the SUT's definition of equals is not what we want to use in our tests, either we can make Equality Assertions on individual fields of the object or we can implement our test-specific equality on a Test-Specific Subclass (page 579 ) of the Expected Object .
Variation: Fuzzy Equality Assertion
When we cannot guarantee an exact match due to variations in precision or expected variations in value, it may be appropriate to use a Fuzzy Equality Assertion . Typically, these assertions look just like Equality Assertions with the addition of an extra "tolerance" or "comparison map" parameter that specifies how close the actual argument must be to the expected one. The most common example of a Fuzzy Equality Assertion is the comparison of floating-point numbers where the limitations of arithmetic precision need to be accounted for by providing a tolerance (the maximum acceptable distance between the two values).
We use the same approach when comparing XML documents where direct string comparisons may result in failure owing to certain fields having unpredictable content. In this case, the "fuzz" specification is a "comparison schema" that specifies which fields need to match or which fields should be ignored. This kind of Equality Assertion is very similar to asserting that a string conforms to a regular expression or other form of pattern matching.
Variation: Stated Outcome Assertion
Stated Outcome Assertions are a way of saying exactly what the outcome should be without passing an expected value as an argument. The outcome must be common enough to warrant a special Assertion Method . The most common examples are as follows:
-
assertTrue(aBooleanExpression), which fails if the expression evaluates to FALSE -
assertNotNull(anObjectReference), which fails if theobjectReferencedoesn't refer to a valid object
Stated Outcome Assertions are often used as Guard Assertions (page 490 ) to avoid Conditional Test Logic .
Variation: Expected Exception Assertion
In languages that support block closures, we can use a variation of a Stated Outcome Assertion that takes an additional parameter specifying the kind of exception we expect. We can use this Expected Exception Assertion to say, "Run this block and verify that the following exception is thrown." This format is more compact than using a try/catch construct. Some typical examples follow:
-
should: [aBlockToExecute] raise: expectedExceptionin Smalltalk's SUnit -
assert_raises( expectedError) { codeToExecute }in Ruby's Test::Unit
Variation: Single-Outcome Assertion
A Single-Outcome Assertion always behaves the same way. The most commonly used Single-Outcome Assertion is fail , which causes a test to be treated as a failure. It is typically used in two circumstances:
-
As an Unfinished Test Assertion (page 494 ) when a test is first identified and implemented as a nearly empty Test Method . By including a call to
fail, we can have the Test Runner (page 377 ) remind us that we still have a test to finish writing. -
As part of a
try/catch(or equivalent) block in an Expected Exception Test (see Test Method ) by including a call tofailin thetryblock immediately after the call that is expected to throw an exception. If we don't want to assert something about the exception that was caught, we can avoid an empty catch block by using the Single-Outcome Assertionsuccessto document that this is the expected outcome.
One circumstance in which we really should not use Single-Outcome Assertions is in Conditional Test Logic . There is almost never a good reason to include conditional logic in a Test Method, as there is usually a more declarative way to handle this situation using other styles of Assertion Methods . For example, use of Guard Assertions results in tests that are more easily understood and less likely to yield incorrect results.
Motivating Example
The following example illustrates the kind of code that would be required for each item we wanted to verify if we did not have Assertion Methods . All we really want to do is this:
if (x.equals(y)) {
throw new AssertionFailedError(
"expected: <" + x.toString() +
"> but found: <" + y.toString() + ">");
} else { // Okay, continue
// ...
}
Unfortunately, this code will cause a NullPointerException if x is null, and it would be hard to distinguish this exception from an error in the SUT. Thus we need to put some guard clauses around this functionality so that we always throw an AssertionFailedException :
if (x == null) { // cannot do null.equals(null)
if (y == null ) { // they are both null so equal
return;
} else {
throw new AssertionFailedError(
"expected null but found: <" + y.toString() +">");
}
} else if (!x.equals(y)) { // comparable but not equal!
throw new AssertionFailedError(
"expected: <" + x.toString() +
"> but found: <" + y.toString() + ">");
} // equal
Yikes! That got pretty messy. And we'll have to do the same thing for every attribute we want to verify? This is not good. There must be a better way.
Refactoring Notes
Luckily for us, the inventors of xUnit recognized this problem and did the requisite Extract Method [Fowler] refactoring to create a library of Assertion Methods that we can call instead. We simply replace the mess of in-line if statements and thrown exceptions with a call to the appropriate Assertion Method . The next example is the code for the JUnit assertEquals method. Although the intent of this example is the same as the code we wrote earlier, it has been rewritten in terms of guard clauses that identify when things are equal.
/**
* Asserts that two objects are equal. If they are not,
* an AssertionFailedError is thrown with the given message.
*/
static public void assertEquals(String message,
Object expected,
Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && expected.equals(actual))
return;
failNotEquals(message, expected, actual);
}
The method failNotEquals is a Test Utility Method that fails the test and provides a diagnostic assertion message.
Example: Equality Assertion
Here is the same assertion logic recoded to take advantage of JUnit's Equality Assertion :
assertEquals( x, y );
Here is the same assertion coded in C#. Note the classname qualifier and the resulting difference in the method name:
Assert.AreEqual( x, y );
Example: Fuzzy Equality Assertion
To compare two floating-point numbers (which are rarely ever really equal), we specify the acceptable differences using a Fuzzy Equality Assertion:
assertEquals( 3.1415, diameter/2/radius, 0.001);
assertEquals( expectedXml, actualXml, elementsToCompare );
Example: Stated Outcome Assertion
To insist that a particular outcome has occurred, we use a Stated Outcome Assertion:
assertNotNull( a );
assertTrue( b > c );
assertNonZero( b );
Example: Expected Exception Assertion
Here is an example of how we verify that the correct exception was raised when we have blocks. In Smalltalk's SUnit, it looks like this:
self
should: [Flight new mileage: -1122]
raise: RuntimeError new 'Should have raised error'
The should: indicates the block of code to run (surrounded by square brackets), while the raise: specifies the expected exception object. In Ruby, it looks like this:
assert_raises( RuntimeError,
"Should have raised error")
{flight.setMileage(-1122) }
The Ruby language syntax also lets us use this "control structure"-style syntax by delimiting the block using do/end instead of curly braces:
assert_raises( RuntimeError, "Should have raised error") do
flight.setMileage(-1122)
end
Example: Single-Outcome Assertion
To fail the test, use the Single Outcome Assertion:
fail( "Expected an exception" );
unfinishedTest();
Assertion Message
How do we structure our test logic to know which assertion failed?
We include a descriptive string argument in each call to an Assertion Method.
We make tests Self-Checking (see page 26 ) by including calls to Assertion Methods (page 362 ) that specify the expected outcome. When a test fails, the Test Runner (page 377 ) writes an entry to the test result log.
A well-crafted Assertion Message makes it very easy to determine which assertion failed and exactly what the symptoms were when the failure happened.
How It Works
Every Assertion Method takes an optional string parameter that is included in the failure log. When the condition being asserted is not true, the Assertion Message is output to the Test Runner's log along with whatever output the assertion method normally generates.
When to Use It
There are two schools of thought on this subject. Test drivers who belong to the "single assertion per Test Method" school believe that they don't need to include Assertion Messages because only one assertion can possibly fail and, therefore, they always know exactly which assertion happened. They count on the Assertion Method to include the arguments (e.g., expected "x" but was "y") but they don't need to include a message.
Conversely, people who find themselves coding several or many assertion method calls in their tests should strongly consider including a message that at least distinguishes which assertion failed. This information is especially important if the tests are frequently run using a Command-Line Test Runner (see Test Runner ), which rarely provides failure location information.
Implementation Notes
It is easy to state that we need a message for each assertion method call—but what should we say in the message? It is useful to take a moment as we write each assertion and ask ourselves what the person reading the failure log would hope to get out of it.
Variation: Assertion-Identifying Message
When we include several assertions of the same type in the same Test Method (page 348 ), we make it more difficult to determine exactly which one failed the test. By including some unique text in each Assertion Message , we can make it very easy to determine which assertion method call failed. A common practice is to use the name of the variable or attribute being asserted on as the message. This technique is very simple and requires very little thought. Another option is to number the assertions. This information would certainly be unique but understanding it may be less intuitive as we would have to look at the code to determine which assertion was failing.
Variation: Expectation-Describing Message
When a test fails, we know what has actually happened. The big question is, "What should have happened?" There are several ways of documenting the expected behavior for the test reader. For example, we could place comments in the test code. A better solution is to include a description of the expectation in the Assertion Message . While this is done automatically for an Equality Assertion (see Assertion Method ), we need to provide this information ourselves for any Stated Outcome Assertions (see Assertion Method ).
Variation: Argument-Describing Message
Some types of Assertion Methods provide less helpful failure messages than others. Among the worst are Stated Outcome Assertions such as assertTrue(aBooleanExpression) . When they fail, all we know is that the stated outcome did not occur. In these cases we can include the expression that was being evaluated (including the actual values) as part of the Assertion Message text. The test maintainer can then examine the failure log and determine what was being evaluated and why it caused the test to fail.
Motivating Example
assertTrue( a > b );
assertTrue( b > c );
This code emits a failure message—something like "Assertion Failed." From this output, we cannot even tell which of the two Assertion Messages failed. Not very useful, is it?
Refactoring Notes
Fixing this problem is a simple matter of adding one more parameter to each Assertion Method call. In this case, we want to communicate that we are expecting "a" to be greater than "b". Of course, it would also be useful to be able to see what the values of "a" and "b" actually were. We can add both pieces of information into the Assertion Message through some judicious string concatenation.
Example: Expectation-Describing Message
Here is the same test with the Argument-Describing Message added:
assertTrue( "Expected a > b but a was '" + a.toString() +
"' and b was '" + b.toString() + "'",
a.gt(b) );
assertTrue( "Expected b > c but b was '" + b.toString() +
"' and c was '" + c.toString + "'",
b > c );
This will now result in a useful failure message:
Assertion Failed. Expected a > b but a was '17' and b was '19'.
Of course, this output would be even more meaningful if the variables had Intent-Revealing Names [SBPP] !
Testcase Class
Also known as
Test Fixture
Where do we put our test code?
We group a set of related Test Methods on a single Testcase Class.
We put our test logic into Test Methods (page 348 ) but those Test Methods need to be associated with a class. A Testcase Class gives us a place to host those methods that we can later turn into Testcase Objects (page 382 ).
How It Works
We collect all Test Methods that are related in some way onto a special kind of class, the Testcase Class. At runtime, the Testcase Class acts as a Test Suite Factory (see Test Enumeration on page 399 ) that creates a Testcase Object for each Test Method. It adds all of these objects to a Test Suite Object (page 387 ) that the Test Runner (page 377 ) will use to run them all.
Why We Do This
In object-oriented languages, we prefer to put our Test Methods onto a class rather than having them as global functions or procedures (even if that is allowed). By making them instance methods of a Testcase Class , we can create a Testcase Object for each test by instantiating the Testcase Class once for each Test Method . This strategy allows us to manipulate the Test Methods at runtime.
Class–Instance Duality
Back in high school physics, we learned about the "wave–particle duality" of light. Sometimes light acts like a particle (e.g., going through a small aperture), and sometimes it acts like a wave (e.g., rainbows). The behavior of Testcase Classes (page 373 ) sometimes reminds me of this concept. Let me explain why.
Developers new to xUnit often ask, "Why is the class we subclass called TestCase when we have several Test Methods on it? Shouldn't it be called TestSuite ?" These questions make a lot of sense when we are focused primarily on the view of the class when we are writing the test code as opposed to when we are running the code.
When we are writing test code, we concentrate on the Test Methods . The Testcase Class is primarily just a place to put the methods. About the only time we think of objects is when we use Implicit Setup (page 424 ) and need to create fields (instance variables) to hold them between the invocation of the setUp method and when they are used in the Test Method . When developers new to xUnit test automation are writing their first tests, they tend to code by example. Following an existing example is a good way to get something working quickly but it doesn't necessarily help the developer understand what is really going on.
At runtime, the xUnit framework typically creates one instance of the Testcase Class for each Test Method . The Testcase Class acts as a Test Suite Factory (see Test Enumeration on page 399 ) that builds a Test Suite Object (page 387 ) containing all the instances of itself, one instance for each Test Method . Now, it's not very often that a static method on a class returns an instance of another class containing many instances of itself. If this behavior wasn't odd enough, the fact that xUnit reports the test failures using the Test Method name can be enough to obscure from many test automaters the existence of "objects inside."
When we examine the object relationships at runtime, things become a bit clearer. The Test Suite Object returned by the Test Suite Factory contains one or more Testcase Objects (page 382 ). So far, so good. Each of these objects is an instance of our Testcase Class . Each instance is configured to run one of the Test Methods . More importantly, each will run a different Test Method . (How this happens is described in more detail in Test Discovery on page 393 .) So each instance of our Testcase Class is, indeed, a test case. The Test Methods are just how we tell each instance what it should test.
Further Reading
Martin Fowler has a great piece on his blog about this issue called "JUnit New Instance" [JNI] .
We could, of course, implement each Test Method on a separate class—but that creates additional overhead and clutters the class namespace. It also makes it harder (although not impossible) to reuse functionality between tests.
Implementation Notes
Most of the complexity of writing tests involves how to write the Test Methods: what to include in-line and what to factor out into Test Utility Methods (page 599 ), how to Isolate the SUT (see page 43 ), and so on.
The real magic associated with the Testcase Class occurs at runtime and is described in Testcase Object and Test Runner . As far as we are concerned, all we have to do is write some Test Methods that contain our test logic and let the Test Runner work its magic. We can avoid Test Code Duplication (page 213 ) by using an Extract Method [Fowler] refactoring to factor out common code into Test Utility Methods . These methods can be left on the Testcase Class or they can be moved to an Abstract Testcase superclass (see Testcase Superclass on page 638 ), a Test Helper class (page 643 ), or a Test Helper Mixin (see Testcase Superclass ).
Example: Testcase Class
Here is an example of a simple Testcase Class :
public class TestScheduleFlight extends TestCase {
public void testUnscheduled_shouldEndUpInScheduled() throws Exception {
Flight flight = FlightTestHelper.
getAnonymousFlightInUnscheduledState();
flight.schedule();
assertTrue( "isScheduled()", flight.isScheduled());
}
public void testScheduledState_shouldThrowInvalidRequestEx()
throws Exception {
Flight flight = FlightTestHelper.
getAnonymousFlightInScheduledState();
try {
flight.schedule();
fail("not allowed in scheduled state");
} catch (InvalidRequestException e) {
assertEquals("InvalidRequestException.getRequest()",
"schedule",
e.getRequest());
assertTrue( "isScheduled()", flight.isScheduled());
}
}
public void testAwaitingApproval_shouldThrowInvalidRequestEx()
throws Exception {
Flight flight = FlightTestHelper.
getAnonymousFlightInAwaitingApprovalState();
try {
flight.schedule();
fail("not allowed in schedule state");
} catch (InvalidRequestException e) {
assertEquals("InvalidRequestException.getRequest()",
"schedule",
e.getRequest());
assertTrue( "isAwaitingApproval()",
flight.isAwaitingApproval());
}
}
}
Further Reading
In some variants of xUnit (most notably VbUnit and NUnit), the Testcase Class is called a test fixture. This usage should not be confused with the test fixture (or test context) that consists of everything we need to have in place before we can start exercising the SUT. 3 Neither should it be confused with the fixture term as used by the Fit framework, which is the Adapter [GOF] that interacts with the Fit table and thereby implements a Data-Driven Test (page 288 ) Interpreter [GOF] .
Test Runner
How do we run the tests?
We define an application that instantiates a Test Suite Object and executes all the Testcase Objects it contains.
Assuming we have defined our Test Methods (page 348 ) on one or more Testcase Classes (page 373 ), how do we actually cause the Test Automation Frameworks (page 298 ) to run our tests?
How It Works
Each member of the xUnit family of Test Automation Frameworks provides some form of command-line or graphical application that can be used to run our automated tests and report on the results. The Test Runner uses Test Enumeration (page 399 ), Test Discovery (page 393 ), or Test Selection (page 403 ) to obtain a Composite [GOF] test object. The latter may either be a single Testcase Object (page 382 ), a Test Suite Object (page 387 ), or a Composite test suite (a Suite of Suites ; see Test Suite Object ). Because all of these objects implement the same interface, the Test Runner need not care whether it is dealing with a single test or a multilevel suite. The Test Runner keeps track of, and reports on, how many tests it has run, how many tests had failed assertions, and how many tests raised errors or exceptions.
Why We Do This
We wouldn't want each test automater to have to provide a special means of running his or her own test suites. That requirement would just get in the way of our ability to simultaneously run all the tests automated by different people. By providing a standard Test Runner , we encourage developers to make it easy to run tests written by different people. We can also provide different ways of running the same tests.
Implementation Notes
Several styles of Test Runners are available. The most common variations are running tests from within an IDE and running tests from the command line. All of these schemes depend on the fact that all Testcase Objects implement a standard interface.
Standard Test Interface
Statically typed languages (such as Java and C#) typically include an interface type (fully abstract class) that defines the interface that all Testcase Objects and Test Suite Objects must implement. Some languages (such as C# and Java 5.0) "mix" in the implementation by using class attributes or annotations on the Testcase Class . In dynamically typed languages, this interface may not exist explicitly. Instead, each implementation class simply implements the standard interface methods. Typically, the standard test interface includes methods on it to count the available tests and to run the tests. Where the framework supports Test Enumeration, each Testcase Class and test suite class must also implement the Test Suite Factory method (see Test Enumeration on page 399 ), which is typically called suite .
Variation: Graphical Test Runner
A Graphical Test Runner is typically a desktop application or part of an IDE (either built-in or a plug-in) for running tests. (See Figure 19.1 .) At least one, IeUnit, runs inside a Web browser rather than an IDE. The most common feature of the Graphical Test Runner is some sort of real-time progress indicator. This monitor typically includes a running count of test failures and errors and often includes a colored progress bar that starts off green and turns red as soon as an error or failure is encountered. Some members of the xUnit family include a graphical Test Tree Explorer as a means to drill down and run a single test from within a Suite of Suites .
Here is the Graphical Test Runner from the JUnit plug-in for Eclipse:
Figure 19.1. Graphical Test Runner from the JUnit plug-in for Eclipse Java IDE.
The red bar near the top indicates that at least one test has failed. The upper text pane shows a list of test failures and test errors. The lower pane shows the traceback from the failed test selected in the upper pane.
Variation: Command-Line Test Runner
Command-Line Test Runners are designed to be used from an operating system command line or from batch files or shell scripts. They are very handy when working remotely via remote shells or when running the tests from a build script such as "make," Ant, or a continuous integration tool such as "Cruise Control."
The following example shows how to run an runit (one of the xUnit implementations for the Ruby programming language) test from the command line:
>ruby testrunner.rb c:/examples/tests/SmellHandlerTest.rb
Loaded suite SmellHandlerTest
Started
.....
Finished in 0.016 seconds.
5 tests, 6 assertions, 0 failures, 0 errors
>Exit code: 0
The first line is the invocation at the command prompt. In this example we are running the tests defined in a single Testcase Class , SmellHandlerTest . The next two lines are the initial feedback as the tests begin. The series of dots indicates the tests' progress, one per test completed. This particular Command-Line Test Runner replaces the dot with an "E" or an "F" if the test produces an error or fails. The last three lines are summary statistics that provide an overview of what happened. Typically, the exit code is set to the total number of failed/error tests so that a non-zero exit code can be interpreted easily as a build failure when run from an automated build tool.
Variation: File System Test Runner
Some Command-Line Test Runners provide the option of searching a specified directory for all files that are tests and running them all at once. This automated Testcase Class Discovery (see Test Discovery ) avoids the need to build the Suite of Suites in code ( Test Enumeration ) and helps avoid Lost Tests (see Production Bugs on page 268 ).
In addition, some external tools will search the file system for files matching specific patterns and then invoke an arbitrary command against the matched files. These files can be passed to the Test Runner from a build tool.
Variation: Test Tree Explorer
Members of the xUnit family that turn each Test Method into a Testcase Object can manipulate the tests easily. Many of them provide a graphical representation of the Suite of Suites and allow the user to select an entire Test Suite Object or a single Testcase Object to run. This eliminates the need to create a Single Test Suite (see Named Test Suite on page 592 ) class to run a single test.
Figure 19.2 shows the Test Tree Explorer of JUnit plug-in for Eclipse shown "popped out" over other Eclipse views:
Figure 19.2. JUnit's Test Tree Explorer shown inside Eclipse Java IDE.
The left pane of the IDE is the JUnit view within Eclipse. The progress bar appears at the top of the view, the upper pane is the Test Tree Explorer, and the lower pane is the traceback for the currently selected test failure. Note that some Test Suite Objects in the Test Tree Explorer are "open," revealing their contents; others are closed down. The colored annotation next to each Testcase Object shows its status; the annotations for each Test Suite Object indicate whether any contained Testcase Objects failed or produced an error. The Test Suite Object called " Test for com.clrstream.ex8.test " is a Suite of Suites for the package " com.clrstream.ex8.test "; " Test for allJUnitTests " is the topmost Suite of Suites for running all the tests.
Testcase Object
How do we run the tests?
We create a Command object for each test and call the run method when we wish to execute it.
The Test Runner (page 377 ) needs a way to find and invoke the appropriate Test Methods (page 348 ) and to present the results to the user. Many Graphical Test Runners (see Test Runner ) let the user drill down into the tree of tests and pick individual tests to run. This capability requires that the Test Runner be able to inspect and manipulate the tests at runtime.
How It Works
We instantiate a Command [GOF] object to represent each Test Method that should execute. We use the Testcase Class (page 373 ) as a Test Suite Factory to create a Test Suite Object (page 387 ) to hold all the Testcase Objects for a particular Testcase Class . We can use either Test Discovery (page 393 ) or Test Enumeration to create the Testcase Objects .
Why We Do This
Treating tests as first-class objects opens up many new possibilities that are not available to us if we treat the tests as simple procedures. It is a lot easier for the Test Runner of the Test Automation Framework (page 298 ) to manipulate tests when they are objects. We can hold them in collections ( Test Suite Objects ), iterate over them, invoke them, and so on.
Most members of the xUnit family create a separate Testcase Object for each test to isolate the tests from one another as prescribed by Independent Test (see page 42 ). Unfortunately, there is always an exception (see the sidebar " There's Always an Exception " on page 384 ), and users of the affected Test Automation Frameworks need to be a bit more cautious.
Implementation Notes
Each Testcase Object implements a standard test interface so that the Test Runner does not need to know the specific interface for each test. This scheme allows each Testcase Object to act as a Command object [GOF] . This allows us to build collections of these Testcase Objects , which we can then iterate across to do counting, running, displaying, and other operations.
In most programming languages, we need to create a class to define the behavior of the Testcase Objects . We could create a separate Testcase Class for each Testcase Object. It is more convenient to host many Test Methods on a single Testcase Class, however, as this strategy results in fewer classes to manage and facilitates reuse of Test Utility Methods (page 599 ). This approach requires that each Testcase Object of the Testcase Class have a way to determine which Test Method it should invoke. Pluggable Behavior [SBPP] is the most common way to do this. The constructor of the Testcase Class takes the name of the method to be invoked as a parameter and stores this name in an instance variable. When the Test Runner invokes the run method on the Testcase Object , it uses reflection to find and invoke the method whose name is in the instance variable.
There's Always an Exception
Whether we are learning to conjugate verbs in a new language or looking for patterns in how software is built, there's always an exception!
One of the most notable exceptions in the xUnit family relates to the use of a Testcase Object (page 382 ) to represent each Test Method (page 348 ) at runtime. This key design feature of xUnit offers a way to achieve an Independent Test (see page 42 ). The only members of the xUnit family that don't follow this scheme are TestNG and NUnit (version 2.x). For the reasons described below, the builders of NUnit 2.0 chose to stray from the well-worn path of one Testcase Object per Test Method and create only a single instance of the Testcase Class (page 373 ). This instance, which they call the test fixture, is then reused for each Test Method. One of the authors of NUnit 2.0, James Newkirk, writes:
I think one of the biggest screw-ups that was made when we wrote NUnit V2.0 was to not create a new instance of the test fixture class for each contained test method. I say "we" but I think this one was my fault. I did not quite understand the reasoning in JUnit for creating a new instance of the test fixture for each test method. I look back now and see that reusing the instance for each test method allows someone to store a member variable from one test and use it in another. This can introduce execution-order dependencies, which for this type of testing is an anti-pattern. It is much better to fully isolate each test method from the others. This requires that a new object be created for each test method.
Unfortunately, this has some very interesting—and undesirable—consequences when one is familiar with the "JUnit New Instance Behavior" of a separate Testcase Object per method. Because the object is reused, any objects it refers to via an instance variable are available to all subsequent tests. This results in an implicit Shared Fixture (page 317 ) along with all the forms of Erratic Tests (page 228 ) that go with it. James goes on to say:
Since it would be difficult to change the way that NUnit works now, and too many people would complain, I now make all of the member variables in test fixture classes static. It's almost like truth in advertising. The result is that there is only one instance of this variable, no matter how many test fixture objects are created. If the variable is static, then someone who may not be familiar with how NUnit executes would not assume that a new one is created before each test is executed. This is the closest I can get to how JUnit works without changing the way that NUnit executes test methods.
Martin Fowler felt this exception was important enough that he wrote an article about why JUnit's approach is correct. See http://martinfowler.com/bliki/JunitNewInstance.html .
Example: Testcase Object
The main evidence of the existence of Testcase Objects appears in the Test Tree Explorer (see Test Runner ) when we "drill down" into the Test Suite Object to expose the Testcase Objects it contains. Let's look at an example from the JUnit Graphical Test Runner that is built into Eclipse. Here's the list of objects created from the sample code from the write-up of Testcase Class:
TestSuite("...flightstate.featuretests.AllTests")
TestSuite("...flightstate.featuretests.TestApproveFlight")
TestApproveFlight("testScheduledState_shouldThrowIn..ReEx")
TestApproveFlight("testUnsheduled_shouldEndUpInAwai..oval")
TestApproveFlight("testAwaitingApproval_shouldThrow..stEx")
TestApproveFlight("testWithNullArgument_shouldThrow..ntEx")
TestApproveFlight("testWithInvalidApprover_shouldTh..ntEx")
TestSuite("...flightstate.featuretests.TestDescheduleFlight")
TestDescheduleFlight("testScheduled_shouldEndUpInSc..tate")
TestDescheduleFlight("testUnscheduled_shouldThrowIn..stEx")
TestDescheduleFlight("testAwaitingApproval_shouldTh..stEx")
TestSuite("...flightstate.featuretests.TestRequestApproval")
TestRequestApproval("testScheduledState_shouldThrow..stEx")
TestRequestApproval("testUnsheduledState_shouldEndU..oval")
TestRequestApproval("testAwaitingApprovalState_shou..stEx")
TestSuite("...flightstate.featuretests.TestScheduleFlight")
TestScheduleFlight("testUnscheduled_shouldEndUpInSc..uled")
TestScheduleFlight("testScheduledState_shouldThrowI..stEx")
TestScheduleFlight("testAwaitingApproval_shouldThro..stEx")
The name outside the parentheses is the name of the class; the string inside the parentheses is the name of the object created from that class. By convention, the name of the Test Method 4 to be run is used as the name of the Testcase Object , and the name of a Test Suite Object is whatever string was passed to the Test Suite Object constructor. In this example we've used the full package and classname of the Testcase Class.
Figure 19.3. A suite of Test Case Objects shown in the JUnit Test Tree Explorer.
Test Suite Object
How do we run the tests when we have many tests to run?
We define a collection class that implements the standard test interface and use it to run a set of related Testcase Objects.
Given that we have created Test Methods (page 348 ) containing our test logic and placed them on a Testcase Class (page 373 ) so we can construct a Testcase Object (page 382 ) for each test, it would be nice to be able to run these tests as a single user operation.
How It Works
We define a Composite [GOF] Testcase Object called a Test Suite Object to hold the collection of individual Testcase Objects to execute. When we want to run all tests in the test suite at once, the Test Runner (page 377 ) asks the Test Suite Object to run all its tests.
Why We Do This
Treating test suites as first-class objects makes it easier for the Test Runner of the Test Automation Framework (page 298 ) to manipulate tests in the test suite. With or without a Test Suite Object , the Test Runner would have to hold some kind of collection of Testcase Objects (so that we could iterate over them, count them, and so on). When we make the collection "smart," it becomes a simple matter to add other uses such as the Suite of Suites .
Variation: Testcase Class Suite
To run all the Test Methods in a single Testcase Class, we simply build a Test Suite Object for the Testcase Class and add one Testcase Object for each Test Method . This allows us to run all the Test Methods in the Testcase Class simply by passing the name of the Testcase Class to the Test Runner .
Variation: Suite of Suites
We can build up larger Named Test Suites (page 592 ) by organizing smaller test suites into a tree structure. The Composite pattern makes this organization invisible to the Test Runner, allowing it to treat a Suite of Suites exactly the same way it treats a simple Testcase Class Suite or a single Testcase Object .
Implementation Notes
As a Composite object, each Test Suite Object implements the same interface as a simple Testcase Object. Thus neither the Test Runner nor the Test Suite Object needs to be aware of whether it is holding a reference to a single test or an entire suite. This makes it easier to implement any operations that involve iterating across all the tests such as counting, running, and displaying.
Before we can do anything with our Test Suite Object , we must construct it. We can choose from several options to do so:
- Test Discovery (page 393 ): We can let the Test Automation Framework discover our Testcase Classes and Test Methods for us.
- Test Enumeration (page 399 ): We can write code that enumerates which Test Methods we want to include in a Test Suite Object . This usually involves creating a Test Suite Factory (see Test Enumeration ).
- Test Selection (page 403 ): We can specify which subset of the Testcase Objects we want to include from an existing Test Suite Object .
Variation: Test Suite Procedure
Sometimes we have to write code in programming or scripting languages that do not support objects. Given that we have written a number of Test Methods , we need to give the Test Runner some way to find the tests. A Test Suite Procedure allows us to enumerate all the tests we want to run by invoking each test in turn. The calls to each test are hard-coded within the body of the Test Suite Object . Of course, a Test Suite Procedure may call several other Test Suite Procedures to realize a Suite of Suites .
The major disadvantage of this approach is that it forces us into Test Enumeration, which increases both the effort required to write tests and the likelihood of Lost Tests (see Production Bugs on page 268 ). Because we do not treat our code as "data," we lose the ability to manipulate the code at runtime. As a consequence, it is more difficult to build a Graphical Test Runner (see Test Runner ) with a hierarchy (tree) view of our Suite of Suites .
Example: Test Suite Object
Most members of the xUnit family implement Test Discovery, so there isn't much of an example of Test Suite Object to see. The main evidence of the existence of Test Suite Objects appears in the Test Tree Explorer (see Test Runner and Figure 19.4 ) when we "drill down" into the Test Suite Object to expose the Testcase Objects it contains. Here's an example from the JUnit Graphical Test Runner built into Eclipse:
Figure 19.4. A Test Suite Object as viewed in JUnit's Test Tree Explorer.
Example: Suite of Suites Built Using Test Enumeration
Here is an example of using Test Enumeration to construct a Suite of Suites:
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for allJunitTests");
suite.addTestSuite(
com.clrstream.camug.example.test.InvoiceTest.class);
suite.addTest(com.clrstream.ex7.test.AllTests.suite());
suite.addTest(com.clrstream.ex8.test.AllTests.suite());
suite.addTestSuite(com.xunitpatterns.guardassertion.Example.class);
return suite;
}
}
The first and last lines add the Test Suite Objects created from a single Testcase Class. Each of the middle two lines calls the Test Suite Factory for another Suite of Suites . The Test Suite Object we return is likely at least three levels deep:
- The Test Suite Object we instantiated and populated before returning
-
The
AllTestsTest Suite Objects returned by the two calls to factory methods - The Test Suite Objects for each of the Testcase Classes aggregated into those Test Suite Objects
This is illustrated in the following tree of objects:
TestSuite("Test for allJunitTests");
TestSuite("com.clrstream.camug.example.test.InvoiceTest")
TestCase("testInvoice_addLineItem")
...
TestCase("testRemoveLineItemsForProduct_oneOfTwo")
TestSuite("com.clrstream.ex7.test.AllTests")
TestSuite("com.clrstream.ex7.test.TimeDisplayTest")
TestCase("testDisplayCurrentTime_AtMidnight")
TestCase("testDisplayCurrentTime_AtOneMinAfterMidnight")
TestCase("testDisplayCurrentTime_AtOneMinuteBeforeNoon")
TestCase("testDisplayCurrentTime_AtNoon")
...
TestSuite("com.clrstream.ex7.test.TimeDisplaySolutionTest")
TestCase("testDisplayCurrentTime_AtMidnight")
TestCase("testDisplayCurrentTime_AtOneMinAfterMidnight")
TestCase("testDisplayCurrentTime_AtOneMinuteBeforeNoon")
TestCase("testDisplayCurrentTime_AtNoon")
...
TestSuite("com.clrstream.ex8.test.AllTests")
TestSuite("com.clrstream.ex8.FlightMgntFacadeTest")
TestCase("testAddFlight")
TestCase("testAddFlightLogging")
TestCase("testRemoveFlight")
TestCase("testRemoveFlightLogging")
...
TestSuite("com.xunitpatterns.guardassertion.Example")
TestCase("testWithConditionals")
TestCase("testWithoutConditionals")
...
Note that this class doesn't subclass any other class. It does need to import TestSuite and the classes it is using as Test Suite Factories .
Example: Test Suite Procedure
In the early days of agile software development, before any agile project management tools were available, I built a set of Excel spreadsheets for managing tasks and user stories. To make life simpler, I automated frequently performed tasks such as sorting all stories by release and iteration, sorting tasks by iteration and status, and so on. Eventually, I got bold enough to write a macro (a program, really) that would sum up the estimated and actual effort of all tasks for each story. At this point, the code was becoming somewhat complex and was more challenging to maintain. In particular, if one of the named ranges used by the sorting macros was accidentally deleted, the macro would produce an error.
Unfortunately, there was no xUnit framework for VBA at the time, so all of this work was done without Tests as Safety Net (see page 24 ). Here is the main program of the reporting macro. All output was written to a new sheet in the workbook.
'Main Macro
Sub summarizeActivities()
Call VerifyVersionCompatability
Call initialize
Call SortByActivity
For row = firstTaskDataRow To lastTaskDataRow
If numberOfNumberlessTasks < MaxNumberlessTasks Then
thisActivity =
ActiveSheet.Cells(row, TaskActivityColumn).Value
If thisActivity <> currentActivity Then
Call finalizeCurrentActivityTotals
currentActivity = thisActivity
Call initializeCurrentActivityTotals
End If
Call accumulateActivityTotals(row)
Else
lastTaskDataRow = row ' end the For loop right away
End If
Next row
Call cleanUp
End Sub
Without any tests or Test Automation Framework , I had to do what I could to introduce some kind of regression testing. In this case, it was enough of a challenge (and a win) just to be able to exercise all the macros. If they ran to completion, it was a much better indication that I hadn't broken anything major than not running the macros at all. Because VBA is based on Visual Basic 5, it has no classes. Thus we have no Testcase Class and no runtime Testcase Objects . The following is an example of the various Test Suite Procedures and the Test Methods my tests called:
Sub TestAll()
Call TestAllStoryMacros
Call TestAllTaskMacros
Call TestReportingMacros
Call TestToolbarMenus 'All The Same
End Sub
Sub TestAllStoryMacros()
Call TestActivitySorting
Call TestStoryHiding
Call ReportSuccess("All Story Macros")
End Sub
Sub TestActivitySorting()
Call SortStoriesbyAreaAndNumber
Call SortActivitiesByIteration
Call SortActivitiesByIterationAndOrder
Call SortActivitiesByNumber
Call SortActivitiesByPercentDone
End Sub
Sub TestReportingMacros()
Call summarizeActivities
End Sub
The first Test Suite Procedure is a Suite of Suites ; the second Test Suite Procedure is the equivalent of a single Test Suite Object . The third Sub is the Test Method for exercising all of the sorting macros. The last Sub exercises the summarizeActivities macro using a Prebuilt Fixture (page 429 ). 5
Test Discovery
How does the Test Runner know which tests to run?
The Test Automation Framework discovers all tests that belong to the test suite automatically.
Given that we have written a number of Test Methods (page 348 ) on one or more Testcase Classes (page 373 ), we need to give the Test Runner (page 377 ) some way to find the tests. Test Discovery eliminates most of the hassles associated with Test Enumeration (page 399 ).
How It Works
The Test Automation Framework (page 298 ) uses runtime reflection (or compile-time knowledge) to discover all Test Methods that belong to the test suite and/or all Test Suite Objects (page 387 ) that belong to a Suite of Suites (see Test Suite Object ). It then builds up the Test Suite Objects containing the corresponding Testcase Objects (page 382 ) and other Test Suite Objects in preparation for running all the tests.
When to Use It
We should use Test Discovery whenever our Test Automation Framework supports it. This pattern reduces the effort required to automate tests and greatly reduces the possibility of Lost Tests (see Production Bugs on page 268 ). The only times to consider using Test Enumeration are (1) when our framework does not support Test Discovery and (2) when we wish to define a Named Test Suite (page 592 ) that consists of a subset of tests 6 chosen from other test suites and the Test Automation Framework does not support Test Selection (page 403 ). It is not uncommon to combine Test Suite Enumeration (see Test Enumeration ) with Test Method Discovery ; the reverse is less common.
Implementation Notes
Building the Suite of Suites to be executed by the Test Runner involves two steps. First, we must find all Test Methods to be included in each Test Suite Object. Second, we must find all Test Suite Objects to be included in the test run, albeit not necessarily in this order. Each of these steps may be done manually via Test Method Enumeration (see Test Enumeration ) and Test Suite Enumeration or automatically via Test Method Discovery and Testcase Class Discovery .
Variation: Testcase Class Discovery
Testcase Class Discovery is the process by which the Test Automation Framework discovers the Testcase Classes on which it should do Test Method Discovery . One solution involves tagging each Testcase Class by subclassing a Testcase Superclass (page 638 ) or implementing a Marker Interface [PJV1]. Another alternative, used in the .NET languages and newer versions of JUnit, is to use a class attribute (e.g., "[Test Fixture]" ) or annotation (e.g., "@Testcase" ) to identify each Testcase Class . Yet another solution is to put all Testcase Classes into a common directory and point the Test Runner or some other program at this directory. A fourth solution is to follow a Testcase Class naming convention and use an external program to find all files matching this naming pattern. Whichever way we choose to perform this task, once a Testcase Class has been discovered we can proceed to either Test Method Discovery or Test Method Enumeration.
Variation: Test Method Discovery
Test Method Discovery involves providing a way for the Test Automation Framework to discover the Test Methods in our Testcase Classes . There are two basic ways to indicate that a method of a Testcase Class is a Test Method . The more traditional approach is to use a Test Method naming convention such as "starts with 'test'." The Test Automation Framework then iterates over all methods of the Testcase Class , selects those that start with the string "test" (e.g., testCounters ), and calls the one-argument constructor to create the Testcase Object for that Test Method . The other alternative, which is used in the .NET languages and newer versions of JUnit, is to use a method attribute (e.g., "[Test]" ) or annotation (e.g., "@Test" ) to identify each Test Method .
Motivating Example
The following example illustrates the kind of code that would be required for each Test Method to do Test Method Enumeration if we did not have Test Discovery available:
public:
static CppUnit::Test *suite()
{
CppUnit::TestSuite *suite =
new CppUnit::TestSuite( "ComplexNumberTest" );
suite>addTest(
new CppUnit::TestCaller<ComplexNumberTest>(
"testEquality",
&ComplexNumberTest::testEquality ) );
suite>addTest(
new CppUnit::TestCaller<ComplexNumberTest>(
"testAddition",
&ComplexNumberTest::testAddition ) );
return suite;
}
This example is from the tutorial for an earlier version of CppUnit. Newer versions no longer require this approach.
Refactoring Notes
Luckily for the users of existing xUnit family members, the inventors of xUnit realized the importance of Test Discovery. Therefore all we have to do is follow their advice on how to identify our test methods. If the developers of our xUnit version used a naming convention, we may have to do a Rename Method [Fowler] refactoring to get xUnit to discover our Test Method . If they implemented method attributes, we just add the appropriate attribute to our Test Methods .
Example: Test Method Discovery (Using Method Naming and Compiler Macro)
When the programming language is capable of managing the tests as objects and invoking the methods but cannot easily find all methods to use as tests, we may need to give it a small push as encouragement to do so. Newer versions of CppUnit provide a macro that finds all Test Methods at compile time and generates the code to build the test suite as illustrated in the previous example. The following code snippet triggers the Test Method Discovery :
CPPUNIT_TEST_SUITE_REGISTRATION( FlightManagementFacadeTest );
This macro uses a method naming convention to determine which methods ("member functions") it should turn into Testcase Objects by wrapping each with a TestCaller , much like in the manual example we saw earlier.
Example: Test Method Discovery (Using Method Naming)
The following examples are more notable for the code that is missing than for the code that is present. Note that there is no code to add the Test Methods to the Test Suite Object .
In this Java example, the framework automatically runs all test methods that start with "test" and have no arguments (a total of two):
public class TimeDisplayTest extends TestCase {
public void testDisplayCurrentTime_AtMidnight()
throws Exception {
// Set up SUT
TimeDisplay theTimeDisplay = new TimeDisplay();
// Exercise SUT
String actualTimeString =
theTimeDisplay.getCurrentTimeAsHtmlFragment();
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">Midnight</span>";
assertEquals( "Midnight",
expectedTimeString,
actualTimeString);
}
public void testDisplayCurrentTime_AtOneMinuteAfterMidnight()
throws Exception {
// Set up SUT
TimeDisplay actualTimeDisplay = new TimeDisplay();
// Exercise SUT
String actualTimeString =
actualTimeDisplay.getCurrentTimeAsHtmlFragment();
// Verify outcome
String expectedTimeString =
"<span class=\"tinyBoldText\">12:01 AM</span>";
assertEquals( "12:01 AM",
expectedTimeString,
actualTimeString);
}
}
Example: Test Method Discovery (Using Method Attributes)
In this C# example, the tests are labeled with the method attribute [Test]. Both CsUnit and NUnit use this way of identifying Test Methods .
[Test]
public void testFlightMileage_asKm()
{
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
newFlight.setMileage(1122);
// exercise mileage translator
int actualKilometres = newFlight.getMileageAsKm();
int expectedKilometres = 1810;
// verify results
Assert.AreEqual( expectedKilometres, actualKilometres);
}
[Test]
[ExpectedException(typeof(InvalidArgumentException))]
public void testSetMileage_invalidInput_attribute()
{
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
// exercise SUT
newFlight.setMileage(-1122);
}
Example: Testcase Class Discovery (Using Class Attributes)
Here is an example of using a class attribute to identify a Testcase Class (called a "Test Fixture" in NUnit) to the Test Runner :
[TestFixture]
public class SampleTestcase
{
}
Example: Testcase Class Discovery (Using Common Location and Testcase Superclass)
The following Ruby example finds all files with the .rb extension in the "tests" directory and requires them from this file. This causes Test::Unit to look for all tests in each file because the Testcase Class in each file extends Test::Unit::TestCase .
Dir['tests/*.rb'].each do |each|
require each
end
The Dir['tests/*.rb'] returns a collection of files over which the each method iterates with the block containing "require each" to implement Testcase Class Discovery . The Ruby interpreter and Test::Unit finish the job by doing Test Method Discovery on each required class.
Test Enumeration
Also known as
Test Suite Factory
How does the Test Runner know which tests to run?
The test automater manually writes the code that enumerates all tests that belong to the test suite.
Given that we have written a number of Test Methods (page 348 ) on one or more Testcase Classes (page 373 ), we need to give the Test Runner (page 377 ) some way to find the tests. Test Enumeration is the way we do so when we lack support for Test Discovery (page 393 ).
How It Works
The test automater manually writes the code that enumerates all Test Methods that belong to the test suite and/or all Test Suite Objects (page 387 ) that belong to a Suite of Suites (see Test Suite Object ). This is typically done by implementing the method suite either on a Testcase Class for Test Method Enumeration or on a Test Suite Factory for Test Suite Enumeration .
When to Use It
We need to use Test Enumeration if our Test Automation Framework (page 298 ) does not support Test Discovery . We can also choose to use Test Enumeration when we wish to define a Named Test Suite (page 592 ) that consists of a subset of tests 7 chosen from other test suites and the framework does not support Test Selection (page 403 ).
Many members of the xUnit family support Test Discovery at the Test Method level but force us to use Test Enumeration at the Testcase Class level.
Implementation Notes
Building the Suite of Suites to be executed by the Test Runner involves two steps. First, we must find all Test Methods to be included in each Test Suite Object. Second, we must find all Test Suite Objects to be included in the test run, albeit not necessarily in this order. Each of these steps may be done manually via Test Method Enumeration and Test Suite Enumeration or automatically via Test Method Discovery (see Test Discovery ) and Testcase Class Discovery (see Test Discovery ). When done manually, we typically use a "Test Suite Factory" that returns the Test Suite Object .
Variation: Test Suite Enumeration
Many members of the xUnit family require that we provide a Test Suite Factory that builds the top-level Suite of Suites (often called "AllTests") as means to specify which Test Suite Objects we would like to include in a test run. We do so by providing a class method on a factory class; this Factory Method [GOF] is called suite in most members of the xUnit family. Inside the suite method we use calls to methods such as addTest to add each nested Test Suite Object to the suite we are building.
Although this approach is fairly flexible, it can result in Lost Tests (see Production Bugs on page 268 ). The alternative is to let the development tools build the AllTests Suite (see Named Test Suite ) automatically or to use a Test Runner that finds all test suites in a file system directory automatically. For example, NUnit provides a built-in mechanism that implements Testcase Class Discovery at the assembly level. We can also use third-party tools such as Ant to find all Testcase Class files in a directory structure.
Even in statically typed languages such as Java, the Test Suite Factory (see Test Enumeration on page 399 ) does not need to subclass a specific class or implement a specific interface. Instead, the only dependencies are on the generic Test Suite Object class it returns and the Testcase Classes or Test Suite Factories it asks for the nested suites.
Variation: Test Method Enumeration
Many members of the xUnit family now support Test Method Discovery. If we happen to be using a version that does not, we need to find all Test Methods in a Testcase Class , turn them into Testcase Objects (page 382 ), and put them into a Test Suite Object . We implement Test Method Enumeration by providing a class method, typically called suite , on the Testcase Class itself.
The capability to construct an object that calls an arbitrary method is often inherited from the Test Automation Framework via a Testcase Superclass (page 638 ) or mixed in via a class attribute or Include directive. In some members of the xUnit family, this Pluggable Behavior [SBPP] capability is provided by a separate class (see the CppUnit example below).
Variation: Direct Test Method Invocation
In the pure procedural world where we cannot treat a Test Method as an object or data item, we have no choice but to hand-code a Test Suite Procedure (see Test Suite Object ) for each test suite. This procedure then calls each Test Method (or other Test Suite Procedures ) one by one.
Example: Test Method Enumeration in CppUnit
Early versions of most xUnit family members required that the test automater add each Test Method manually. Those versions that cannot use reflection still have this requirement. Here is an example from an older version of CppUnit that uses this approach:
public:
static CppUnit::Test *suite()
{
CppUnit::TestSuite *suite =
new CppUnit::TestSuite( "ComplexNumberTest" );
suite>addTest(
new CppUnit::TestCaller<ComplexNumberTest>(
"testEquality",
&ComplexNumberTest::testEquality ) );
suite>addTest(
new CppUnit::TestCaller<ComplexNumberTest>(
"testAddition",
&ComplexNumberTest::testAddition ) );
return suite;
}
This example also illustrates how CppUnit wraps each Test Method with an instance of a class ( TestCaller ) to turn it into a Testcase Object .
Example: Test Method Invocation (Hard-Coded)
The following example is from a test suite for a program written in VBA (Visual Basic for Applications, the macro language used in Microsoft Office products), which lacks support for objects:
Sub TestAllStoryMacros()
Call TestActivitySorting
Call TestStoryHiding
Call ReportSuccess("All Story Macros")
End Sub
Example: Test Suite Enumeration
We can use Test Suite Enumeration when the Test Automation Framework does not support Test Discovery or when we want to define a Named Test Suite that includes only a subset of the tests.
The main drawback of using Test Suite Enumeration for running all tests is the potential for Lost Tests if we forget to include a new test suite in the AllTests Suite . This risk can be reduced by paying attention to the number of tests that were run when we first checked out the code and ensuring that the number run just before check-in goes up by the number of new tests we added.
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for allJunitTests");
//$JUnit-BEGIN$
suite.addTestSuite(
com.clrstream.camug.example.test.InvoiceTest.class);
suite.addTest(com.clrstream.ex7.test.AllTests.suite());
suite.addTest(com.clrstream.ex8.test.AllTests.suite());
suite.addTestSuite(
com.xunitpatterns.guardassertion.Example.class);
//$JUnit-END$
return suite;
}
}
In this example, we take advantage of the IDE's ability to (re)generate the AllTests suite for us. (Eclipse will regenerate the code between the two marker comments whenever we request it to do so.) We still need to remember to regenerate the suite occasionally, but this approach goes a long way toward avoiding Lost Tests in the absence of Test Discovery .
Test Selection
How does the Test Runner know which tests to run?
The Test Automation Framework selects the Test Methods to be run at runtime based on attributes of the tests.
Given that we have written a number of Test Methods (page 348 ) on one or more Testcase Classes (page 373 ), we need to give the Test Runner (page 377 ) some way to find those tests. Test Selection is a way to pick subsets of tests dynamically.
How It Works
The test automater specifies the subset of tests to be run when invoking the Test Runner by providing test selection criteria. These selection criteria may be based on implicit or explicit attributes of the Testcase Classes or Test Methods .
When to Use It
We should use Test Selection when we wish to run a subset of tests chosen from other test suites and we do not want to maintain a separate structure built using Test Enumeration (page 399 ). A Smoke Test [SCM] suite is a common usage; see Named Test Suite (page 592 ) for other uses.
Implementation Notes
Test Selection can be implemented either by creating a Subset Suite (see Named Test Suite ) from an existing Test Suite Object (page 387 ) or by skipping some of the tests within the Test Suite Object as we execute the Testcase Objects (page 382 ) it contains.
As with Test Discovery (page 393 ) and Test Enumeration , Test Selection can be applied at two different levels: selecting Testcase Classes or selecting Test Methods . Test Selection can be built into the Test Automation Framework (page 298 ) or it can be implemented more crudely as part of the build task.
Variation: Testcase Class Selection
We can select the Testcase Classes to be examined for Test Methods in several ways. The crudest way to do Testcase Class Selection is simply to place the Testcase Classes into test packages based on some criteria. Unfortunately, this strategy works only for a single test classification scheme and is likely to reduce the value of Tests as Documentation (see page 23 ). A somewhat more flexible approach is to use a naming convention such as "contains 'WebServer'" to select only those classes that verify the behavior of certain parts of the system. This, too, is somewhat constrained in its utility.
The most flexible way to implement Test Selection is within the Test Automation Framework . We can use class attributes (.NET) or annotations (Java) to indicate characteristics of the Testcase Class . The same technique can also be applied at the Test Method level.
Variation: Test Method Selection
When implemented as part of the Test Automation Framework , Test Method Selection can be done by specifying the "category" (or categories) to which a Test Method belongs. This usually requires language support for method attributes (.NET) or annotations (Java). It could also be based on a method name scheme, although this approach is not as flexible and would require tighter coupling to the Test Runner .
Example: Testcase Class Selection Using Class Attributes
The following example of Testcase Class Selection is from NUnit. The class attribute Category("FastSuite") indicates that all tests in this Testcase Class should be included (or excluded) when the category "FastSuite" is specified in the Test Runner .
[TestFixture]
[Category("FastSuite")]
public class CategorizedTests
{
[Test]
public void testFlightConstructor_OK()
// Methods omitted
}
Example: Test Method Selection Using Method Attributes
This example of Test Method Selection is from NUnit. The method attribute Category("SmokeTest") indicates that this Test Method should be included (or excluded) when the category "SmokeTest" is specified in the Test Runner .
[Test]
[Category("SmokeTests")]
public void testFlightMileage_asKm()
{
// set up fixture
Flight newFlight = new Flight(validFlightNumber);
newFlight.setMileage(1122);
// exercise mileage translator
int actualKilometres = newFlight.getMileageAsKm();
int expectedKilometres = 1810;
// verify results
Assert.AreEqual( expectedKilometres, actualKilometres);
}