Result Verification
About This Chapter
Chapter 8 , Transient Fixture Management, and Chapter 9 , Persistent Fixture Management, described how to set up the test fixture and how to tear it down after exercising the SUT. This chapter introduces a variety of options for verifying that the SUT has behaved correctly, including exercising the SUT and comparing the actual outcome with the expected outcome.
Making Tests Self-Checking
One of the key characteristics of tests automated using xUnit is that they can be (and should be) Self-Checking Tests (see Goals of Test Automation on page 21 ). This characteristic makes them cost-effective enough to be run very frequently. Most members of the xUnit family come with a collection of built-in Assertion Methods (page 362 ) and some documentation that tells us which one to use when. On the surface this sounds pretty simple—but there's a lot more to writing good tests than just calling the built-in Assertion Methods . We also need to learn key techniques for making tests easy to understand and for avoiding and removing Test Code Duplication (page 213 ).
A key challenge in coding the assertions is getting access to the information we want to compare with the expected results. This is where observation points come into play; they provide a window into the state or behavior of the SUT so that we can pass it to the Assertion Methods . Observation points for information accessible via synchronous method calls are relatively straightforward; observation points for other kinds of information can be quite challenging, which is precisely what makes automated unit testing so interesting.
Assertions are usually—but not always—called from within the Test Method (page 348 ) body right after the SUT has been exercised. Some test automaters put assertions after the fixture setup phase of the test to ensure that the fixture is set up correctly. This practice almost always contributes to Obscure Tests (page 186 ), so I would rather write unit tests for the Test Utility Methods (page 599 ). 1 Some styles of testing do require us to set up our expectations before we exercise the SUT; this topic is discussed in more detail in Chapter 11 , Using Test Doubles . We'll see several examples of calling Assertion Methods from within Test Utility Methods in this chapter.
One possible—though rarely used—place to put calls to Assertion Methods is in the tearDown method used in Implicit Teardown (page 516 ). Because this method is run for every test, whether that test passed or failed (as long as the setUp method succeeded), one can put assertions here. This scheme involves the same trade-off as using Implicit Setup (page 424 ) for building our test fixture; it's less visible but done automatically. See the sidebar " Using Delta Assertions to Detect Data Leakage " (page 487 ) for an example of putting assertions in the tearDown method used by Implicit Teardown of a superclass to detect when tests leave leftover test objects in the database.
Verify State or Behavior?
Ultimately, test automation is about verifying the behavior of the SUT. Some aspects of the SUT's behavior can be verified directly; the value returned by a function is a good example. Other aspects of the behavior are more easily verified indirectly by looking at the state of some object. We can verify the actual behavior of the SUT in our tests in two ways:
- We can verify the states of various objects affected by the SUT by extracting each state using an observation point and using assertions to compare it to the expected state.
- We can verify the behavior of the SUT directly by using observation points inserted between the SUT and its depended-on component (DOC) to monitor its interactions (in the form of the method calls it makes) and comparing those method calls with what we expected.
State Verification (page 462 ) is done using assertions and is the simpler of the two approaches. Behavior Verification (page 468 ) is more complicated and builds on the assertion techniques we use for verifying state.
State Verification
The "normal" way to verify the expected outcome has occurred is called State Verification ( Figure 10.1 ). First we exercise the SUT; then we examine the post-exercise state of the SUT using assertions. We may also examine anything returned by the SUT as a result of the method call we made to exercise it. What is most notable is what we do not do: We do not instrument the SUT in any way to detect how it interacts with other components of the system. That is, we inspect only direct outputs and we use only direct method calls as our observation points.
Figure 10.1. State Verification. In State Verification, we assert that the SUT and any objects it returns are in the expected state after we have exercised the SUT. We "pay no attention to the man behind the curtain."
State Verification can be done in two slightly different ways. Procedural State Verification (see State Verification ) involves writing a sequence of assertions that pick apart the end state of the SUT and verify that it is as expected. Expected Object (see State Verification ) is a way of describing the expected state in such a way that it can be compared with a single Assertion Method call; this approach minimizes Test Code Duplication and increases test clarity (more on this later in this chapter). With both strategies, we can use either "built-in" assertions or Custom Assertions (page 474 ).
Using Built-in Assertions
We use the assertions provided by our testing framework to specify what should be and depend on them to tell us when it isn't so! But simply using the built-in assertions is only a small part of the story.
The simplest form of result verification is the assertion in which we specify what should be true. Most members of the xUnit family support a range of different Assertion Methods, including the following:
-
Stated Outcome Assertions (see Assertion Method ) such as
assertTrue (aBooleanExpression) -
Simple Equality Assertions such as
assertEquals(expected, actual) -
Fuzzy Equality Assertions such as
assertEquals(expected, actual, tolerance), which are used for comparing floats
Of course, the test programming language has some influence on the nature of the assertions. In JUnit, SUnit, CppUnit, NUnit, and CsUnit, most of the Equality Assertions take a pair of Object s as their parameters. Some languages support "overloading" of method parameter types so we can have different implementations of an assertion for different types of objects. Some languages—C, for example—don't support objects, so we cannot compare objects, only values.
There are several issues to consider when using Assertion Methods . Naturally, the first priority is the verification of all things that should be true. The better our assertions, the finer our Safety Net (see page 24 ) and the higher our confidence in our code. The second priority is the documentation value of the assertions. Each test should make it very clear that "When the system is in state S1 and I do X, the result should be R and the system should be in state S2." We put the system into state S1 in our fixture setup logic. "I do X" corresponds to the exercise SUT phase of the test. "The result is R" and "the system is in state S2" are implemented using assertions. Thus we want to write our assertions in such a way that they succinctly describe "R" and "S2."
Another thing to consider is that when the test fails, we want the failure message to tell us enough to enable us to identify the problem. 2 Therefore, we should almost always include an Assertion Message (page 370 ) as the optional message parameter (assuming our xUnit family member has one!). This tactic avoids the possibility of us playing Assertion Roulette (page 224 ), in which we cannot even tell which assertion is failing without running the test interactively; it makes Integration Build [SCM] failures much easier to reproduce and fix. It also makes troubleshooting broken tests easier by telling us what should have happened; the actual outcome tells us what did happen!
When we use a Stated Outcome Assertion (such as JUnit's assertTrue ), the failure messages tend to be unhelpful (e.g., "Assertion failed"). We can make the assertion output much more specific by using an Argument-Describing Message (see Assertion Message ) constructed by incorporating useful bits of data into the message. A good start is to include each of the values in the expression passed as the Assertion Method's arguments.
Delta Assertions
When using a Shared Fixture (page 317 ), we may find that we have Interacting Tests (see Erratic Test on page 228 ) because each test adds more objects/rows into the database and we can never be certain exactly what should be there after the SUT has been exercised. One way to deal with this uncertainty is to use Delta Assertions (page 485 ) to verify only the newly added objects/rows. In this approach, we take some sort of "snapshot" of the relevant tables/classes at the beginning of the test; we then remove these tables/classes from the collection of actual objects/rows produced at the end of the test before comparing them to the Expected Objects . Although this tactic can introduce significant extra complexity into the tests, the added complexity can be refactored into Custom Assertions and/or Verification Methods (see Custom Assertion ). The "before" snapshot may be taken on an in-line basis within the Test Method or in the setUp method if all setup occurs before the Test Method is invoked [e.g., Implicit Setup , a Shared Fixture, or a Prebuilt Fixture (page 429 )].
External Result Verification
Thus far we have described only conventional "in-memory" verification of the expected results. In fact, another approach is possible—one that involves storing the expected and actual results in files and using an external comparison program to report on any differences. This is, in effect, a form of Custom Assertion that uses a "deep compare" on two file references. The comparison program often needs to be told which parts of the files to ignore (or these parts need to be stripped out first), effectively making this a Fuzzy Equality Assertion .
External result verification is particularly appropriate for automating acceptance tests for regression-testing an application that hasn't changed very much. The major disadvantage of this approach is that we almost always end up with a Mystery Guest (see Obscure Test ) from the test reader's perspective because the expected results are not visible inside the test. One way to avoid this problem is to have the test write the contents of the expected file, thereby making the contents visible to the test reader. This step is practical only if the amount of data is quite small—another argument in favor of a Minimal Fixture (page 302 ).
Verifying Behavior
Verifying behavior is more complicated than verifying state because behavior is dynamic. We have to catch the SUT "in the act" as it generates indirect outputs to the objects it depends on ( Figure 10.2 ). Two basic styles of behavior verification are worth discussing: Procedural Behavior Verification and Expected Behavior . Both require a mechanism to access the outgoing method calls of the SUT (its indirect outputs). This and other uses of Test Doubles (page 522 ) are described in more detail in Chapter 11 , Using Test Doubles .
Figure 10.2. Behavior Verification. In Behavior Verification, we focus our assertions on the indirect outputs (outgoing interfaces) of the SUT. This typically involves replacing the DOC with something that facilitates observing and verifying the outgoing calls.
Procedural Behavior Verification
In Procedural Behavior Verification, we capture the behavior of the SUT as it executes and save that data for later retrieval. The test then compares each output of the SUT (one by one) with the corresponding expected output. Thus, in Procedural Behavior Verification, the test executes a procedure (a set of steps) to verify the behavior.
public void testRemoveFlightLogging_recordingTestStub()
throws Exception {
// fixture setup
FlightDto expectedFlightDto = createAnUnregFlight();
FlightManagementFacade facade =
new FlightManagementFacadeImpl();
// Test Double setup
AuditLogSpy logSpy = new AuditLogSpy();
facade.setAuditLog(logSpy);
// exercise
facade.removeFlight(expectedFlightDto.getFlightNumber());
// verify
assertEquals("number of calls", 1,
logSpy.getNumberOfCalls());
assertEquals("action code",
Helper.REMOVE_FLIGHT_ACTION_CODE,
logSpy.getActionCode());
assertEquals("date", helper.getTodaysDateWithoutTime(),
logSpy.getDate());
assertEquals("user", Helper.TEST_USER_NAME,
logSpy.getUser());
assertEquals("detail",
expectedFlightDto.getFlightNumber(),
logSpy.getDetail());
}
The key challenge in Procedural Behavior Verification is capturing the behavior as it occurs and saving it until the test is ready to use this information. This task is accomplished by configuring the SUT to use a Test Spy (page 538 ) or a Self Shunt (see Hard-Coded Test Double on page 568 ) 3 instead of the depended-on class. After the SUT has been exercised, the test retrieves the recording of the behavior and verifies it using assertions.
Expected Behavior Specification
If we can build an Expected Object and compare it with the actual object returned by the SUT for verifying state, can we do something similar for verifying behavior? Yes, we can and do. Expected Behavior is often used in conjunction with layer-crossing tests to verify the indirect outputs of an object or component. We configure a Mock Object (page 544 ) with the method calls we expect the SUT to make to it and install this object before exercising the SUT.
public void testRemoveFlight_JMock() throws Exception {
// fixture setup
FlightDto expectedFlightDto = createAnonRegFlight();
FlightManagementFacade facade =
new FlightManagementFacadeImpl();
// mock configuration
Mock mockLog = mock(AuditLog.class);
mockLog.expects(once()).method("logMessage")
.with(eq(helper.getTodaysDateWithoutTime()),
eq(Helper.TEST_USER_NAME),
eq(Helper.REMOVE_FLIGHT_ACTION_CODE),
eq(expectedFlightDto.getFlightNumber()));
// mock installation
facade.setAuditLog((AuditLog) mockLog.proxy());
// exercise
facade.removeFlight(expectedFlightDto.getFlightNumber());
// verify
// verify() method called automatically by JMock
}
Reducing Test Code Duplication
One of the most common test smells is Test Code Duplication . With every test we write, there is a good chance we have introduced some duplication, but especially if we used "cut and paste" to create a new test from an existing test. Some will argue that duplication in test code is not nearly as bad as duplication in production code. Test Code Duplication is bad if it leads to some other smell such as Fragile Test (page 239 ), Fragile Fixture (see Fragile Test ) , or High Test Maintenance Cost (page 265 ) because too many tests are too closely coupled to the Standard Fixture (page 305 ) or the API of the SUT. In addition, Test Code Duplication may sometimes be a symptom of another problem—namely, the intent of the tests being obscured by too much code (i.e., an Obscure Test ).
In result verification logic, Test Code Duplication usually shows up as a set of repeated assertions. Several techniques are available to reduce the number of assertions in such cases:
- Expected Objects
- Custom Assertions
- Verification Methods
Expected Objects
Often, we will find ourselves doing a series of assertions on different fields of the same object. If we begin repeating this group of assertions (whether multiple times in a single test or in multiple tests), we should look for a way to reduce the Test Code Duplication . The next listing shows one Test Method that compares several attributes of a single object. Many other Test Methods probably require the same sequence of assertions.
public void testInvoice_addLineItem7() {
LineItem expItem = new LineItem(inv, product, QUANTITY);
// Exercise
inv.addItemQuantity(product, QUANTITY);
// Verify
List lineItems = inv.getLineItems();
LineItem actual = (LineItem)lineItems.get(0);
assertEquals(expItem.getInv(), actual.getInv());
assertEquals(expItem.getProd(), actual.getProd());
assertEquals(expItem.getQuantity(), actual.getQuantity());
}
The most obvious alternative is to use a single Equality Assertion to compare two whole objects to each other rather than using many Equality Assertion calls to compare them field by field. If the values are stored in individual variables, we may need to create a new object of the appropriate class and initialize its fields with those values. This technique works as long as we have an equals method that compares only those fields and we have the ability to create the Expected Object at will.
public void testInvoice_addLineItem8() {
LineItem expItem = new LineItem(inv, product, QUANTITY);
// Exercise
inv.addItemQuantity(product, QUANTITY);
// Verify
List lineItems = inv.getLineItems();
LineItem actual = (LineItem)lineItems.get(0);
assertEquals("Item", expItem, actual);
}
But what if we don't want to compare all the fields in an object or the equals method looks for identity rather than equality? What if we want test-specific equality? What if we cannot create an instance of the Expected Object because no constructor exists? In this scenario, we have two options: We can implement a Custom Assertion that defines equality the way we want it or we can implement our test-specific equality in the equals method of the class of the Expected Object we pass to the Assertion Method . This class doesn't need to be the same class as that of the actual object; it just needs to implement equals to compare itself with an instance of the actual object's class. Therefore, it can be a simple Data Transfer Object [CJ2EEP] or it can be a Test-Specific Subclass (page 579 ) of the real (production) class with just the equals method overridden.
Some test automaters don't think we should ever rely on the equals method of the SUT when making assertions because it could change, thereby causing tests that depend on this method to fail (or to miss important differences). I prefer to be pragmatic about this decision. If it seems reasonable to use the equals definition supplied by the SUT, then I do so. If I need something else, I define a Custom Assertion or a test-specific Expected Object class. I also ask myself how hard it would be to change my strategy if the equals method should later change. For example, in statically typed languages that support parameter type overloading (such as Java), we can add a Custom Assertion that uses different parameter types to override the default implementation when specific types are used. This code can often be retrofitted quite easily if a change to equals causes problems at a later date.
Custom Assertions
A Custom Assertion is a domain-specific assertion we write ourselves. Custom Assertions hide the procedure for verifying the results behind a declarative name, making our result verification logic more intent-revealing. They also prevent Obscure Tests by eliminating of a lot of potentially distracting code. Another benefit of moving the code into a Custom Assertion is that the assertion logic can now be unit-tested by writing Custom Assertion Tests (see Custom Assertion ). The assertions are no longer Untestable Test Code (see Hard-to-Test Code on page 209 )!
static void assertLineItemsEqual(
String msg, LineItem exp, LineItem act) {
assertEquals (msg+" Inv", exp.getInv(), act.getInv());
assertEquals (msg+" Prod", exp.getProd(), act.getProd());
assertEquals (msg+" Quan", exp.getQuantity(), act.getQuantity());
}
There are two ways to create Custom Assertions : (1) by refactoring existing complex test code to reduce Test Code Duplication and (2) by coding calls to nonexistent Assertion Methods as we write tests and then filling in the method bodies with the appropriate logic once we land on the suite of Custom Assertions needed by a set of Test Methods . The latter technique is a good way of reminding ourselves what we expect the outcome of exercising the SUT to be, even though we haven't yet written the code to verify it. Either way, the definition of a set of Custom Assertions is the first step toward creating a Higher-Level Language (see page 41 ) for specifying our tests.
When refactoring to Custom Assertions, we simply use Extract Method [Fowler] on the repeated assertions and give the new method an Intent-Revealing Name [SBPP] . We pass in the objects used by the existing verification logic as arguments and include an Assertion Message to differentiate between calls to the same assertion method.
Outcome-Describing Verification Method
Another technique that is born from ruthless refactoring of test code is the "outcome-describing" Verification Method . Suppose we find that a group of tests all have identical exercise SUT and verify outcome sections. Only the setup portion is different for each test. If we do an Extract Method refactoring on the common code and give it a meaningful name, we need less code, achieve more understandable tests, and produce testable verification logic all at the same time! If this isn't a worthwhile reason for refactoring code, then I don't know what else could be.
void assertInvoiceContainsOnlyThisLineItem(
Invoice inv,
LineItem expItem) {
List lineItems = inv.getLineItems();
assertEquals("number of items", lineItems.size(), 1);
LineItem actual = (LineItem)lineItems.get(0);
assertLineItemsEqual("",expItem, actual);
}
The major difference between a Verification Method and a Custom Assertion is that the latter only makes assertions, while the former also interacts with the SUT (typically for the purpose of exercising it). Another difference is that Custom Assertions typically have a standard Equality Assertion signature: assertSomething(message, expected, actual) . In contrast, Verification Methods may have completely arbitrary parameters because they require additional parameters to pass into the SUT. They are, in essence, halfway between a Custom Assertion and a Parameterized Test (page 607 ).
Parameterized and Data-Driven Tests
We can go even further in factoring out the commonality between tests. If the logic to set up the test fixture is the same but uses different data, we can extract the common fixture setup, exercise SUT, and verify outcome phases of the test into a new Parameterized Test method. This Parameterized Test is not called automatically by the Test Automation Framework (page 298 ) because it requires arguments; instead, we define very simple Test Methods for each test, which then call the Parameterized Test and pass in the data required to make this test unique. This data may include that required for fixture setup, exercising the SUT, and the corresponding expected result. In the following tests, the method generateAndVerifyHtml is the Parameterized Test .
def test_extref
sourceXml = "<extref id='abc' />"
expectedHtml = "<a href='abc.html'>abc</a>"
generateAndVerifyHtml(sourceXml,expectedHtml,"<extref>")
end
def test_testterm_normal
sourceXml = "<testterm id='abc'/>"
expectedHtml = "<a href='abc.html'>abc</a>"
generateAndVerifyHtml(sourceXml,expectedHtml,"<testterm>")
end
def test_testterm_plural
sourceXml = "<testterms id='abc'/>"
expectedHtml = "<a href='abc.html'>abcs</a>"
generateAndVerifyHtml(sourceXml,expectedHtml,"<plural>")
end
In a Data-Driven Test (page 288 ), the test case is completely generic and directly executable by the framework; it reads the arguments from a test data file as it executes. Think of a Data-Driven Test as a Parameterized Test turned inside out: A Test Method passes test-specific data to a Parameterized Test ; a Data-Driven Test is the Test Method and reads the test-specific data from a file. The contents of the file are a Higher-Level Language for testing; the Data-Driven Test method is the Interpreter [GOF] of that language. This scheme is the xUnit equivalent of a Fit test. A simple example of a Data-Driven Test method is shown in this code sample written in Ruby:
def test_crossref
executeDataDrivenTest "CrossrefHandlerTest.txt"
end
def executeDataDrivenTest filename
dataFile = File.open(filename)
dataFile.each_line do | line |
desc, action, part2 = line.split(",")
sourceXml, expectedHtml, leftOver = part2.split(",")
if "crossref"==action.strip
generateAndVerifyHtml sourceXml, expectedHtml, desc
else # new "verbs" go before here as elsif's
report_error( "unknown action" + action.strip )
end
end
end
Here is the comma-delimited data file that the Data-Driven Test method reads:
ID, Action, SourceXml, ExpectedHtml
Extref,crossref,<extref id='abc'/>,<a href='abc.html'>abc</a>
TTerm,crossref,<testterm id='abc'/>,<a href='abc.html'>abc</a>
TTerms,crossref,<testterms id='abc'/>,<a href='abc.html'>abcs</a>
Avoiding Conditional Test Logic
Another thing we want to avoid in our tests is conditional logic. Conditional Test Logic (page 200 ) is bad because the same test may execute differently in different circumstances. Conditional Test Logic reduces our trust in the tests because the code in our Test Methods is Untestable Test Code . Why is this important? Because the only way we can verify our Test Method is to manually edit the SUT so that it produces the error we want to be detected. If the Test Method has many paths through it, we need to make sure each path is coded correctly. Isn't it so much simpler just to have only one possible execution path through the test? Let us look at some reasons why we might include conditional logic in our tests:
- We don't want to execute certain assertions because their execution doesn't make sense given what we have already discovered at this point in the test (typically a failure condition).
- We have to allow for various situations in the actual results that we are comparing to the expected results.
- We are trying to reuse a Test Method in several different circumstances (essentially merging several tests into a single Test Method ).
The problem with using Conditional Test Logic in the first two cases is that it makes the code hard to read and may mask cases of reusing test methods via Flexible Tests (see Conditional Test Logic ). The last "reason" is just a bad idea, plain and simple. There are much better ways of reusing test logic than trying to reuse the Test Method itself. We have already seen some of these reuse techniques elsewhere in this chapter (in Reducing Test Code Duplication ), and we will see other ways elsewhere in this book. Just say "no"!
The good news is that it is relatively straightforward to remove all legitimate uses of Conditional Test Logic from our tests.
Eliminating "if" Statements
What should we do when we don't want to execute an assertion because we know it will result in a test error and we would prefer to have a more meaningful test failure message? The normal reaction is to place the assertion inside an "if" statement, as shown in the following listing. Unfortunately, this approach results in Conditional Test Logic, which we would dearly like to avoid because we want exactly the same code to run each time we run the test.
List lineItems = invoice.getLineItems();
if (lineItems.size() == 1) {
LineItem expected =
new LineItem(invoice, product,5,
new BigDecimal("30"),
new BigDecimal("69.96"));
LineItem actItem = (LineItem) lineItems.get(0);
assertEquals("invoice", expected, actItem);
} else {
fail("Invoice should have exactly one line item");
}
The preferred solution is to use a Guard Assertion (page 490 ) as shown in this revised version of the test code:
List lineItems = invoice.getLineItems();
assertEquals("number of items", lineItems.size(), 1);
LineItem expected =
new LineItem(invoice, product, 5,
new BigDecimal("30"),
new BigDecimal("69.96"));
LineItem actItem = (LineItem) lineItems.get(0);
assertEquals("invoice", expected, actItem);
The nice thing about Guard Assertions is that they keep us from hitting the assertion that would cause a test error but without introducing Conditional Test Logic . Once we get used to them, these assertions are fairly obvious and intuitive to read. We may even find ourselves wanting to assert the pre-conditions of our methods in our production code!
Eliminating Loops
Conditional Test Logic may also appear as loops that verify the content of a collection returned by the SUT matches what we expected. Putting loops directly into the Test Method creates three problems:
- It introduces Untestable Test Code because the looping code, which is part of the test, cannot be tested with Fully Automated Tests (see page 26 ).
- It leads to Obscure Tests because all that looping code obscures the real intent: Does or doesn't the collection match?
- It can lead to the project-level smell Developers Not Writing Tests (page 263 ) because the complexity of writing the loops may discourage the developer from writing the Self-Checking Test .
A better solution is to delegate this logic to a Test Utility Method with an Intent-Revealing Name, which can be both tested and reused.
Other Techniques
This section outlines some other techniques for writing easy-to-understand tests.
Working Backward, Outside-In
A useful little trick for writing very intent-revealing code is to work backward. This is an application of Stephen Covey's idea, "Start with the end in mind." To do so, we write the last line of the function or test first. For a function, its whole reason for existence is to return a value; for a procedure, it is to produce one or more side effects by modifying something. For a test, the raison d' tre is to verify that the expected outcome has occurred (by making assertions).
Working backward means we write these assertions first. We assert on the values of suitably named local variables to ensure that the assertion is intent-revealing. The rest of writing the test simply consists of filling in whatever is needed to execute those assertions: We declare variables to hold the assertion arguments and initialize them with the appropriate content. Because at least one argument should have been retrieved from the SUT, we must, of course, invoke the SUT. To do so, we may need some variables to use as SUT arguments. Declaring and initializing a variable after it has been used forces us to understand the variable better when we introduce it. This scheme also results in better variable names and avoids meaningless names like invoice1 and invoice2 .
Working "outside-in" (or "top-down" as it is sometimes called) means staying at a consistent level of abstraction. The Test Method should focus on what we need to have in place to induce the relevant behavior in the SUT. The mechanics of how we reach that place should be delegated to a "lower layer" of test software. In practice, we code this behavior as calls to Test Utility Methods, which allows us to stay focused on the requirements of the SUT as we write each Test Method . We don't need to worry about how we will create that object or verify that outcome; we merely need to describe what that object or outcome should be. The utility method we just used but haven't yet defined acts as a placeholder for the unfinished test automation logic. 4 We can move on to writing the other tests we need for this SUT while they are still fresh in our minds. Later, we can switch to our "toolsmith" hat and implement the Test Utility Methods .
Using Test-Driven Development to Write Test Utility Methods
Once we are finished writing the Test Method(s) that used the Test Utility Method , we can start the process of writing the Test Utility Method itself. Along the way, we can take advantage of test-driven development by writing Test Utility Tests (see Test Utility Method ). It doesn't take very long to write these unit tests that verify the behavior of our Test Utility Methods and we will have much more confidence in them.
We start with the simple case (say, asserting the equality of two identical collections that hold the same item) and work up to the most complicated case that the Test Methods actually require (say, two collections that contain the same two items but in different order). TDD helps us find the minimal implementation of the Test Utility Method , which may be much simpler than a complete generic solution. There is no point in writing generic logic that handles cases that aren't actually needed but it may be worthwhile to include a Guard Assertion or two inside the Custom Assertion to fail tests in cases it doesn't support.
Where to Put Reusable Verification Logic?
Suppose we have decided to use Extract Method refactorings to create some reusable Custom Assertions or we have decided to write our tests in an intent-revealing way using Verification Methods . Where should we put these bits of reusable test logic? The most obvious place is in the Testcase Class (page 373 ) itself. We can allow this logic to be reused more broadly by using a Pull-Up Method [Fowler] refactoring to move them up to a Testcase Superclass (page 638 ) or a Move Method [Fowler] refactoring to move them into a Test Helper (page 643 ). This issue is discussed in more detail in Chapter 12 , Organizing Our Tests .
What's Next?
This discussion of techniques for verifying the expected outcome concludes our introduction to the basic techniques of automating tests using xUnit. Chapter 11 , Using Test Doubles, introduces some advanced techniques involving the use of Test Doubles.