xUnit Test Patterns: Refactoring Test Code and over one million other books are available for Amazon Kindle. Learn more



or
Sign in to turn on 1-Click ordering
Sell Us Your Item
For a $26.85 Gift Card
Trade in
More Buying Choices
Have one to sell? Sell yours here
Start reading xUnit Test Patterns: Refactoring Test Code on your Kindle in under a minute.

Don't have a Kindle? Get your Kindle here, or download a FREE Kindle Reading App.
Sorry, this item is not available in
Image not available for
Color:
Image not available

To view this video download Flash Player

 

xUnit Test Patterns: Refactoring Test Code [Hardcover]

Gerard Meszaros
4.5 out of 5 stars  See all reviews (21 customer reviews)

Buy New
$49.74 & FREE Shipping. Details
Rent
$37.98 & this item ships for FREE with Super Saver Shipping. Details
In Stock.
Ships from and sold by Amazon.com. Gift-wrap available.
In Stock.
Rented by RentU and Fulfilled by Amazon.
Want it Friday, June 21? Choose One-Day Shipping at checkout. Details
Free Two-Day Shipping for College Students with Amazon Student

Formats

Amazon Price New from Used from
Kindle Edition $30.79  
Hardcover $49.74  
Sell Back Your Copy for $26.85
No matter where you bought them, get up to 70% back when you sell your books at Amazon.com.
Used Price$42.48
Trade-in Price$26.85
Price after
Trade-in
$15.63

Book Description

May 31, 2007 0131495054 978-0131495050

Automated testing is a cornerstone of agile development. An effective testing strategy will deliver new functionality more aggressively, accelerate user feedback, and improve quality. However, for many developers, creating effective automated tests is a unique and unfamiliar challenge.

xUnit Test Patterns is the definitive guide to writing automated tests using xUnit, the most popular unit testing framework in use today. Agile coach and test automation expert Gerard Meszaros describes 68 proven patterns for making tests easier to write, understand, and maintain. He then shows you how to make them more robust and repeatable--and far more cost-effective.

Loaded with information, this book feels like three books in one. The first part is a detailed tutorial on test automation that covers everything from test strategy to in-depth test coding. The second part, a catalog of 18 frequently encountered "test smells," provides trouble-shooting guidelines to help you determine the root cause of problems and the most applicable patterns. The third part contains detailed descriptions of each pattern, including refactoring instructions illustrated by extensive code samples in multiple programming languages.

Topics covered include

  • Writing better tests--and writing them faster
  • The four phases of automated tests: fixture setup, exercising the system under test, result verification, and fixture teardown
  • Improving test coverage by isolating software from its environment using Test Stubs and Mock Objects
  • Designing software for greater testability
  • Using test "smells" (including code smells, behavior smells, and project smells) to spot problems and know when and how to eliminate them
  • Refactoring tests for greater simplicity, robustness, and execution speed

This book will benefit developers, managers, and testers working with any agile or conventional development process, whether doing test-driven development or writing the tests last. While the patterns and smells are especially applicable to all members of the xUnit family, they also apply to next-generation behavior-driven development frameworks such as RSpec and JBehave and to other kinds of test automation tools, including recorded test tools and data-driven test tools such as Fit and FitNesse.


Visual Summary of the Pattern Language 
Foreword

Preface

Acknowledgments

Introduction

Refactoring a Test

PART I: The Narratives
Chapter 1 A Brief Tour
Chapter 2 Test Smells
Chapter 3 Goals of Test Automation
Chapter 4 Philosophy of Test Automation
Chapter 5 Principles of Test Automation
Chapter 6 Test Automation Strategy
Chapter 7 xUnit Basics
Chapter 8 Transient Fixture Management
Chapter 9 Persistent Fixture Management
Chapter 10 Result Verification
Chapter 11 Using Test Doubles
Chapter 12 Organizing Our Tests
Chapter 13 Testing with Databases
Chapter 14 A Roadmap to Effective Test Automation
PART II: The Test Smells 
Chapter 15 Code Smells
Chapter 16 Behavior Smells
Chapter 17 Project Smells
PART III: The Patterns 
Chapter 18 Test Strategy Patterns
Chapter 19 xUnit Basics Patterns
Chapter 20 Fixture Setup Patterns
Chapter 21 Result Verification Patterns
Chapter 22 Fixture Teardown Patterns
Chapter 23 Test Double Patterns
Chapter 24 Test Organization Patterns
Chapter 25 Database Patterns
Chapter 26 Design-for-Testability Patterns
Chapter 27 Value Patterns
PART IV: Appendixes
Appendix A Test Refactorings  
Appendix B xUnit Terminology 
Appendix C xUnit Family Members
Appendix D Tools
Appendix E Goals and Principles
Appendix F Smells, Aliases, and Causes
Appendix G Patterns, Aliases, and Variations
Glossary
References 

Index 



Frequently Bought Together

xUnit Test Patterns: Refactoring Test Code + Test Driven Development: By Example + Working Effectively with Legacy Code
Price for all three: $124.83

Buy the selected items together


Editorial Reviews

About the Author

Gerard Meszaros is Chief Scientist and Senior Consultant at ClearStream Consulting, a Calgary-based consultancy specializing in agile development. He has more than a decade of experience with automated unit testing frameworks and is a leading expert in test automation patterns, refactoring of software and tests, and design for testability.

Excerpt. © Reprinted by permission. All rights reserved.

The Value of Self-Testing Code

In Chapter 4 of Refactoring Ref, Martin Fowler writes:

If you look at how most programmers spend their time, you'll find that writing code is actually a small fraction. Some time is spent figuring out what ought to be going on, some time is spent designing, but most time is spent debugging. I'm sure every reader can remember long hours of debugging, often long into the night. Every programmer can tell a story of a bug that took a whole day (or more) to find. Fixing the bug is usually pretty quick, but finding it is a nightmare. And then when you do fix a bug, there's always a chance that anther one will appear and that you might not even notice it until much later. Then you spend ages finding that bug.

Some software is very difficult to test manually. In these cases, we are often forced into writing test programs.

I recall a project I was working on in 1996. My task was to build an event framework that would let client software register for an event and be notified when some other software raised that event (the Observer GOF pattern). I could not think of a way to test this framework without writing some sample client software. I had about 20 different scenarios I needed to test, so I coded up each scenario with the requisite number of observers, events, and event raisers. At first, I logged what was occurring in the console and scanned it manually. This scanning became very tedious very quickly.

Being quite lazy, I naturally looked for an easier way to perform this testing. For each test I populated a Dictionary indexed by the expected event and the expected receiver of it with the name of the receiver as the value. When a particular receiver was notified of the event, it looked in the Dictionary for the entry indexed by itself and the event it had just received. If this entry existed, the receiver removed the entry. If it didn't, the receiver added the entry with an error message saying it was an unexpected event notification.

After running all the tests, the test program merely looked in the Dictionary and printed out its contents if it was not empty. As a result, running all of my tests had a nearly zero cost. The tests either passed quietly or spewed a list of test failures. I had unwittingly discovered the concept of a Mock Object (page 544) and a Test Automation Framework (page 298) out of necessity!

My First XP Project

In late 1999, I attended the OOPSLA conference, where I picked up a copy of Kent Beck's new book, eXtreme Programming Explained XPE. I was used to doing iterative and incremental development and already believed in the value of automated unit testing, although I had not tried to apply it universally. I had a lot of respect for Kent, whom I had known since the first PLoP1 conference in 1994. For all these reasons, I decided that it was worth trying to apply eXtreme Programming on a ClearStream Consulting project. Shortly after OOPSLA, I was fortunate to come across a suitable project for trying out this development approach--namely, an add-on application that interacted with an existing database but had no user interface. The client was open to developing software in a different way.

We started doing eXtreme Programming "by the book" using pretty much all of the practices it recommended, including pair programming, collective ownership, and test-driven development. Of course, we encountered a few challenges in figuring out how to test some aspects of the behavior of the application, but we still managed to write tests for most of the code. Then, as the project progressed, I started to notice a disturbing trend: It was taking longer and longer to implement seemingly similar tasks.

I explained the problem to the developers and asked them to record on each task card how much time had been spent writing new tests, modifying existing tests, and writing the production code. Very quickly, a trend emerged. While the time spent writing new tests and writing the production code seemed to be staying more or less constant, the amount of time spent modifying existing tests was increasing and the developers' estimates were going up as a result. When a developer asked me to pair on a task and we spent 90% of the time modifying existing tests to accommodate a relatively minor change, I knew we had to change something, and soon!

When we analyzed the kinds of compile errors and test failures we were experiencing as we introduced the new functionality, we discovered that many of the tests were affected by changes to methods of the system under test (SUT). This came as no surprise, of course. What was surprising was that most of the impact was felt during the fixture setup part of the test and that the changes were not affecting the core logic of the tests.

This revelation was an important discovery because it showed us that we had the knowledge about how to create the objects of the SUT scattered across most of the tests. In other words, the tests knew too much about nonessential parts of the behavior of the SUT. I say "nonessential" because most of the affected tests did not care about how the objects in the fixture were created; they were interested in ensuring that those objects were in the correct state. Upon further examination, we found that many of the tests were creating identical or nearly identical objects in their test fixtures.

The obvious solution to this problem was to factor out this logic into a small set of Test Utility Methods (page 599). There were several variations:

  • When we had a bunch of tests that needed identical objects, we simply created a method that returned that kind of object ready to use. We now call these Creation Methods (page 415).
  • Some tests needed to specify different values for some attribute of the object. In these cases, we passed that attribute as a parameter to the Parameterized Creation Method (see Creation Method).
  • Some tests wanted to create a malformed object to ensure that the SUT would reject it. Writing a separate Parameterized Creation Method for each attribute cluttered the signature of our Test Helper (page 643), so we created a valid object and then replaced the value of the One Bad Attribute (see Derived Value on page 718).
We had discovered what would become2 our first test automation patterns.

Later, when tests started failing because the database did not like the fact that we were trying to insert another object with the same key that had a unique constraint, we added code to generate the unique key programmatically. We called this variant an Anonymous Creation Method (see Creation Method) to indicate the presence of this added behavior.

Identifying the problem that we now call a Fragile Test (page 239) was an important event on this project, and the subsequent definition of its solution patterns saved this project from possible failure. Without this discovery we would, at best, have abandoned the automated unit tests that we had already built. At worst, the tests would have reduced our productivity so much that we would have been unable to deliver on our commitments to the client. As it turned out, we were able to deliver what we had promised and with very good quality. Yes, the testers3 still found bugs in our code because we were definitely missing some tests. Introducing the changes needed to fix those bugs, once we had figured out what the missing tests needed to look like, was a relatively straightforward process, however.

We were hooked. Automated unit testing and test-driven development really did work, and we have been using them consistently ever since.

As we applied the practices and patterns on subsequent projects, we have run into new problems and challenges. In each case, we have "peeled the onion" to find the root cause and come up with ways to address it. As these techniques have matured, we have added them to our repertoire of techniques for automated unit testing.

We first described some of these patterns in a paper presented at XP2001. In discussions with other participants at that and subsequent conferences, we discovered that many of our peers were using the same or similar techniques. That elevated our methods from "practice" to "pattern" (a recurring solution to a recurring problem in a context). The first paper on test smells RTC was presented at the same conference, building on the concept of code smells first described in Ref.

My Motivation

I am a great believer in the value of automated unit testing. I practiced software development without it for the better part of two decades, and I know that my professional life is much better with it than without it. I believe that the xUnit framework and the automated tests it enables are among the truly great advances in software development. I find it very frustrating when I see companies trying to adopt automated unit testing but being unsuccessful because of a lack of key information and skills.

As a software development consultant with ClearStream Consulting, I see a lot of projects. Sometimes I am called in early on a project to help clients make sure they "do things right." More often than not, however, I am called in when things are already off the rails. As a result, I see a lot of "worst practices" that result in test smells. If I am lucky and I am called early enough, I can help the client recover from the mistakes. If not, the client will likely muddle through less than satisfied with how TDD and automated unit testing worked--and the word goes out that automated unit testing is a waste of time.

In hindsight, most of these mistakes and best practices are easily avoidable given the right knowledge at the right time. But how do you obtain that knowledge without making the mistakes for yourself? At the risk of sounding self-serving, hiring someone who has the knowledge is the most time-efficient way of learning any new practice or technology. According to Gerry Weinberg's "Law of Raspberry Jam" SoC,4<...


Product Details

  • Hardcover: 833 pages
  • Publisher: Addison-Wesley (May 31, 2007)
  • Language: English
  • ISBN-10: 0131495054
  • ISBN-13: 978-0131495050
  • Product Dimensions: 7.2 x 2 x 9.4 inches
  • Shipping Weight: 3.3 pounds (View shipping rates and policies)
  • Average Customer Review: 4.5 out of 5 stars  See all reviews (21 customer reviews)
  • Amazon Best Sellers Rank: #65,637 in Books (See Top 100 in Books)

More About the Author

Discover books, learn about writers, read author blogs, and more.

Customer Reviews

4.5 out of 5 stars
(21)
4.5 out of 5 stars
Most Helpful Customer Reviews
44 of 44 people found the following review helpful
Format:Hardcover
Let me start by stating the obvious: this is a patterns book about the organisation of tests and the workings of the xUnit family of unit testing frameworks. It is _not_ a book about Test Driven Development, although there is material that is pertinent to that. Given that the use of JUnit and TDD is pretty intertwined in the minds of many Java developers, it's worth making this distinction, so you know what sort of book you're getting. Speaking of JUnit, most of the code examples uses Java, although there are some examples in C#, VB and Ruby.

Like Martin Fowler's Patterns of Enterprise Application Architecture, the book is split into two main sections, a narrative that weaves together a lot of the patterns and strategies, and then a catalogue of individual patterns. Between the two, there is a catalogue of 'test smells', similar to the 'code smells' discussed by Fowler in Refactoring, which I would suggest can be read profitably with the narrative section, rather than used as reference material.

There are a lot of patterns here on the mechanics of xUnit, such as 'Test Runner', 'Garbage-Collected Teardown' and 'Named Test Suite'. I was a bit confused about who this material is aimed at -- maybe someone looking at porting xUnit to a new programming language would find it useful, but a lot of it is fairly obvious to anyone who's used an xUnit in a non-trivial fashion (and certainly, if you haven't done so, this book is not a format that makes for a good introduction), or requires playing against xUnit's strengths (e.g.
... Read more ›
Was this review helpful to you?
14 of 14 people found the following review helpful
5.0 out of 5 stars Seminal Work in Test-Driven Development June 16, 2007
Format:Hardcover
We went over 2,000 unit tests this past week during Iteration 72 on our Agile project. Of course, over the course of the last 18-24 months we have removed some tests, and in many cases, refactored the existing tests many times. We also have been learning a whole lot about TDD and the actual domain that we are building and testing. As we were doing this, we were implicitly discovering Test Smells, and discovering test automation patterns. The value in establishing patterns, and more precisely a pattern language in a particular domain are substantial. It's not so much that the "collector" of patterns is defining something new (some often mistakenly criticize pattern books in that regard) that you didn't know, but defining a shared terminology of our practices that we keep doing over and over. To that end, the patterns themselves not only define a shared vocabulary but serve other functions, not the least of which is learning from others. An obvious example of this is Martin's PEAA collection of patterns that enables us to say things like PageController or Lazy Load or TableDataGateway and we all know what it means. In fact, when I am talking about Interaction versus State/Behavior type of testing on CB, and others here use much of this terminology, I am in fact, talking about patterns like TestDoubles and MockObjects, among others.

When I became aware that Gerard Meszaros ' xUnit Test Patterns book was going to ship Friday, I ordered it for overnight delivery on Saturday. I read well over 200 pages yesterday pretty much at one sitting, contented with a book that will change the face of the software industry, just as JUnit and all the other xUnit family have fundamentally altered software development for the better.
... Read more ›
Comment | 
Was this review helpful to you?
16 of 18 people found the following review helpful
5.0 out of 5 stars Fills an important void June 6, 2007
Format:Hardcover
Writing good tests is not easy. Different developers have come up with many techniques to improve tests. You might have used Backdoor Manipulation to make tests faster or used Custom Assertions to make an Obscure Test more readable. Sometimes a failing test caused you to play Assertion Roulette while you were trying to figure out who the Mystery Guest in this test is and what role he plays.

Gerard documented these (and many more) smells and patterns to help you write better tests. If you have written tests, you have probably used some of them, but even then looking at the patterns described in this book will help you tune your technique. For example Custom Assertions should always take the actual and expected values as parameters, so assertMagicObjectsAreEqual(actual, expected) is good, assertEverythingIsAlright(actual) is bad. And now you have a name for this technique, which makes it easier to explain to your fellow developers what you are doing. At 800+ pages you are bound to find plenty of new techniques as well.

If you are worried that this is another work by the pattern weenies, rest assured. The book follows the very simple and pragmatic "How It Works" and "When to Use It" format also used by Martin Fowlers' Patterns of Enterprise Application Architecture.
Comment | 
Was this review helpful to you?
6 of 6 people found the following review helpful
5.0 out of 5 stars A must-have for xUnit practitioners... July 4, 2007
Format:Hardcover
By now, the concept of "patterns" in program design is pretty well accepted. And the concept of test-driven development has a solid foundation also. But are there certain "patterns" to building and running those tests? The answer is yes, and the book that covers it is xUnit Test Patterns: Refactoring Test Code by Gerard Meszaros. If you use any of the xUnit software in your development efforts, you need to have this book...

Contents:
Part 1 - The Narratives: A Brief Tour; Test Smells; Goals of Test Automation; Philosophy of Test Automation; Principles of Test Automation; Test Automation Strategy; xUnit Basics; Transient Fixture Management; Persistent Fixture Management; Result Verification; Using Test Doubles; Organizing Our Tests; Testing with Databases; A Roadmap to Effective Test Automation
Part 2 - The Test Smells: Code Smells; Behavior Smells; Project Smells
Part 3 - The Patterns: Test Strategy Patterns; xUnit Basics Patterns; Fixture Setup Patterns; Result Verification Patterns; Fixture Teardown Patterns; Test Double Patterns; Test Organization Patterns; Database Patterns; Design-for-Testability Patterns; Value Patterns
Part 4 - Appendixes: Test Refactorings; xUnit Terminology; xUnit Family Members; Tools; Goals and Principles; Smells, Aliases, and Causes; Patterns, Aliases, and Variations
Glossary; References; Index

Most of the books that cover xUnit software do so from the perspective of a technical manual. Everything is geared to writing the actual code for the test. Meszaros takes a different tack. He covers more of the "why" behind test writing in xUnit, as well as the basic patterns and principles you should be aware of when you're putting together your tests.
... Read more ›
Comment | 
Was this review helpful to you?
Most Recent Customer Reviews
3.0 out of 5 stars More like a textbook
There's a lot of textbook-style instruction here that I think is overly specific. There are a few good parts as well, like test smells and other general philosophy, but there are... Read more
Published 2 months ago by Eric
5.0 out of 5 stars An authoritative work
Like the rest of the books in Martin Fowler's signature series, this is an authoritative work on the important subject of unit testing. Read more
Published 3 months ago by Puneet S. Lamba
3.0 out of 5 stars Trim out the duplication and it's excellent
This is a really good 300 page book in 800+ pages. Trying to teach myself unit testing, without a more experienced mentor helping me, I ran into a lot of cases where the... Read more
Published 3 months ago by Thomas Panning
4.0 out of 5 stars A monumental work
If you want to know pretty much all there is to know, or at least far more than you really need to know, here's your chance. Read more
Published 5 months ago by H. Hemken
5.0 out of 5 stars Excellent
I think this book is a very good one about patterns and test.
It has good examples and a really helpful approach about test this is a main book about test patterns.
Published 12 months ago by Vanius Zapalowski
5.0 out of 5 stars Authoritative and extremely useful
I think the title is a bit misleading, because this book is about a lot more than just writing good test code. Read more
Published on July 11, 2010 by Jas Bro
5.0 out of 5 stars Principles and Concepts for Pragmatic Test Management
If TDD or its kin survive, it will be largely due to adoption of manageable tactics for testing. This book is unprecedented in supplying principles and conceptual tools hopefully... Read more
Published on April 27, 2010 by Gary
5.0 out of 5 stars Awesome book must have for any software developer
Our team has been doing TDD for 6 years since the seminal Kent Beck book.
We as a team have learnt read and improved our practice over these years but this book has had the... Read more
Published on November 18, 2009 by A. B. Powell
4.0 out of 5 stars Found it
It's what I was looking for. It is giving me a good reference and compass to TDD.
Published on October 29, 2009 by Tech Book Addict
5.0 out of 5 stars Good Desk Reference
Good book, I keep it on my desk at work. There is a pretty substantial website with nearly the same information online, however even after reading most of that site, I still chose... Read more
Published on September 9, 2009 by Tara Nicholson
Search Customer Reviews
Only search this product's reviews

What Other Items Do Customers Buy After Viewing This Item?


Forums

Topic From this Discussion
This book has a web site Be the first to reply
Have something you'd like to share about this product?
Start a new discussion
Topic:
First post:
Prompts for sign-in
 


Search Customer Discussions
Search all Amazon discussions


So You'd Like to...


Create a guide


Look for Similar Items by Category