Jump to ratings and reviews
Rate this book

Martin Fowler Signature Book

xUnit Test Patterns: Refactoring Test Code

Rate this book
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




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



833 pages, Hardcover

First published May 1, 2003

Loading interface...
Loading interface...

About the author

Gerard Meszaros

3 books13 followers

Ratings & Reviews

What do you think?
Rate this book

Friends & Following

Create a free account to discover what your friends think of this book!

Community Reviews

5 stars
211 (31%)
4 stars
279 (41%)
3 stars
137 (20%)
2 stars
38 (5%)
1 star
13 (1%)
Displaying 1 - 30 of 50 reviews
Profile Image for Gleb Sevruk.
21 reviews9 followers
July 12, 2013
I started with some interesting reading - but this was only Preface by Martin Fowler. I stopped reading at 200-th page because it gets too repetitive and makes no sense (just a catalogue with generic programming practices)

If you want to learn testing - I would recommend (in order):
Michael Feathers "Working Effectively with Legacy Code" (explains WHY to write test and how to achieve it)
Roy Osherove "The Art of Unit Testing"
Mark Seemann "Dependency Injection in .NET"

These guys knows what they are writing and how to convey material efficiently
Profile Image for Tom Panning.
44 reviews8 followers
March 8, 2013
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 suggestions in normal unit testing books and guides didn't seem to work. This book had good solutions for many of those problems.

Unfortunately, this book is incredibly repetitive with an unbelievable amount of duplicated content. It was to the point where I could read a new chapter, and for several pages I would swear that I must have already read it because it was so familiar. And when I wanted to look up something I remembered from the book, it was so hard to find it because the same topic is covered in so many places. It's not just that a topic is mentioned in several places and then really discussed in one place. I think Meszaros wanted the first part of the book to be a quick intro, and then the back of the book to be the encyclopedia reference with the full information. But the intros include 80% of the content in the reference section. And just as bad, I think Meszaros broke out the patterns too finely because many of them spend several paragraphs talking about other related patterns. Imagine if the GoF had made the Model, the View, and the Controller three separate patterns, but in each of the three patterns talked about how they fit together, and you'll get an idea.

This book has some great content in a packaging that made me almost give up on it so many times. So it's not junk, but I would consider it a book of last resorts. If you have a unit testing question and can't find the answer anywhere else, try looking in this book.
40 reviews3 followers
November 24, 2013
Эта книга была написана автором в тесном сотрудничестве с Капитаном Очевидность. Вдвоем они руководствовались принципом "лишь повторенное трижды есть истина". Как результат книга полна воды, среди которой очень сложно отыскать крупицы полезной информации. Практически каждое словосочетание в книге (даже если оно самоочевидно) выделено курсивом и предполагает за собой Паттерн. В итоге некоторые Предложения В Книге представляют собой Типографическое Месиво от которого бы известный Отечественный дизайнер С фамилией Лебедев плакал бы Кровавыми Слезами.

Самым полезной частью в книге является введение, которое демонстрирует удачный рефакторинг существующего теста и раскрывает примерно половину содержания книги. Чуть менее содержательна первая часть (примерно до 200-й страницы) в ней (неоднократно) раскрывается все остальное. Оставшиеся страницы нужно читать выборочно, только в том случае если название паттерна почему-то наводит на подозрение что здесь еще осталось что-то неизведанное.

Читать рекомендуется позитивно настроенным терпеливым людям, которые во что бы то ни стало намерены прочитать эту книгу. Даже при этом, для экономии времени, не стоит читать книгу дальше первой части.
407 reviews67 followers
January 6, 2013
This book makes me feel like this practice of cataloguing software patterns is getting out of hand. It started with Design Patterns, a brilliant book that catalogued 9 common software design patterns. It wasn't intended to be exhaustive, just a handful of some of the most useful patterns. Then other books started cataloguing other patterns, in various realms of software. This book catalogues patterns in unit testing, but not just a handful. I counted 68 patterns, including things such as using literal values in your tests. It crosses a line from a few useful patterns to 900 pages of mostly basic programming practices, each described in such detail that you'd think nobody's ever heard of using literal values in their code before!

It's nice to have universal names for various programming techniques, but sometimes it feels like this can just make common techniques sound far more esoteric than they really are. For example, what would you guess "dependency injection" means? Sounds fancy, doesn't it? Like somehow one procedure hacks into another and changes its dependencies? Nope, dependency injection just means the practice of passing a dependency as a parameter.

I did get a couple of nice tips from this book. Not really anything I couldn't have figured out by myself, if I was presented with the problems the patterns were designed to solve. I do feel like I have a better grasp of all the various terminology used in unit testing. But it's certainly not worth 900 pages.
Profile Image for Jo.
37 reviews8 followers
July 25, 2018
The most exhaustive work on test automation practices & patterns I've encountered to date.

The book starts with some general outlines: "why", "how", "when",... but is mostly a smell & pattern catalog -including all the redundancy and back-referencing a pattern language implies-.

Topics covered: designing for testability, organising tests, state vs. behavior verification, setup/teardown patterns, getting untestable code under test, tests and databases, dealing with asynchronicity, ... http://xunitpatterns.com/index.html contains a summary of most topics covered in the book.


Don't read this in a single sitting. Do keep this on hand when you're having problems with a specific test and/or suite and want to build a list of options on how to improve.
Profile Image for Robson Castilho.
227 reviews30 followers
October 3, 2017
Very solid guide about coding high-quality tests.
Being a pattern catalog and a very extensive book, it's better using it as a reference guide or reading it in steps (maybe interleaving it with other books). One issue about being a big pattern catalog is the repetition of samples (and even text) from one pattern to another.
But the major disappointment is not mentioning anything about using Builders for creating Test Data and even Test SUTs (I strongly advice reading about that).
Profile Image for Stijn.
Author 5 books
May 18, 2017
Amazing book! A deep dive into the world of Unit Tests and the Refactoring of Test Code. So many valuable principles and patterns that you can use in your daily practice.
Every individual who calls themselves a 'Professional Developer' MUST read this book.
Profile Image for Thierry de Pauw.
17 reviews4 followers
May 1, 2021
I gave it 4 stars because it is the only patterns book I know of about Unit Testing. You get here a very extensive overview of all patterns related to testing.
Even after 10 years wrestling with legacy code bases I had several aha moments.

To be fair, as some reviewers have already pointed out, the book is quite repetitive. But, well, repetition is a good learning tool ;)

You also need a fair bit of courage to start reading the book when contemplating the thickness of the book :)
Profile Image for Rod Hilton.
150 reviews3,125 followers
August 10, 2012
I know a lot about unit testing. I'm a big TDD advocate, and I've learned an awful lot of lessons about effective unit testing over the years. I could easily give a series of talks on the topic of unit testing.

And yet, I don't think there's a single thing I know about unit testing that isn't covered in xUnit Test Patterns. This book is the bible of unit testing, unbelievably thorough. Nearly every aspect of unit testing is covered (at least that I know about), categorized into patterns and organized into a very, very good book.

The book is huge, clocking it at nearly a thousand pages. The title also isn't terribly accurate, it's really more about the Patterns than the refactoring. But those two issues aside, this book will take you from unit testing novice to unit testing ninja easily.

As with most Patterns books, if you are already well-versed in the topic, you won't learn all that much new except for consistent terminology to apply to your knowledge. I knew most of what was in the book already, and found myself reading the Narratives section and the Test Smells section, but largely skimming the details of the Patterns section itself, most of which is spelled out pretty well in Narratives anyway. Mostly, I learned a lot of new terms that will help me communicate effectively with other developers, and I picked up a bit of new material (mostly from the Test Smells section).

xUnit Test Patterns is an excellent but long (and slightly dry) book that I highly recommend for anyone who has some familiarity with unit testing, but doesn't consider him or herself a pro.
42 reviews2 followers
August 23, 2016
My primary complaint with this book - it's too big. That's a shame - since there is some good stuff in here that needs to be read.

I've seen first hand that 'bad xUnit tests can be worse than having no xUnit tests' - teams sink hours trying to keep their tests green, while the tests are like christmas lights flickering red n green on their own accord.

Tests are code - the same rigor n quality procedures need to be applied for tests. If not the tests can cripple and impede development (instead of being an 'enabler')
Profile Image for Vasili Puchko.
15 reviews3 followers
September 29, 2011
It's the Unit Testing Bible. It's highly informative, it covers almost everything a developer should know about Unit Testing. It's big, but it's a very good time investment if you want to become a great programmer.
Profile Image for Rob.
21 reviews
June 14, 2023
This is a huge, comprehensive book, containing every testing pattern I knew of and many more.

The first ~200 pages build up a convincing narrative of philosophies and practices around automated testing strategy, touching on important patterns as they come up.

The remaining ~600 pages explain each smell and pattern in detail. This pattern catalogue shouldn't be read front to back. I skimmed it, and paid more attention to interesting or important patterns. I'm sure I will refer back to it in the future.

The most interesting set of patterns for me are the ones related to test doubles. The author's categorisation of different types of test double (stubs, spies, mocks and fakes) clears up a lot of the arguments seen online about the subject, and helped me to understand the different reasons we replace dependencies during tests. For example, mocking is useful if you need to verify indirect outputs (if they would otherwise be untested), and stubbing is useful if I need to provide specific indirect inputs (e.g. to inject an exception or another output that's hard to generate from the real dependency).

The strength of this book is that it doesn't present just a single view of testing, but many. The author treats each point of view fairly and respectfully, explaining the rationale behind every pattern, where it can be useful, and what are its drawbacks.

The only thing I think was missing from this book was: what should the system under test be? One class, one module? Should you test non-public classes and methods? Should you test only through the ports of the ports and adapters pattern? It's mentioned that it's best to test through the "front door", i.e. the public API, and that system-level tests can test through the UI or, ideally, directly on the service layer, and in most of the examples it's implied that we're only testing one class or a small group of related classes. It would have been interesting to read some discussion specifically about test granularity.
7 reviews
October 31, 2021
It is a reference book and a good one at this.

When I started reading the intimidating number of pages I soon realized that they reduce fast, since I skipped the redundant parts. But redundancy is very important for a reference book and will help me a lot when I need to find information when I need it. And this is the second aspect it is very good at: Structure. It is very well structured with different approaches to the topic and a comprehensive index and appendix.

The only caveat I see is, that it could use a new, updated edition. Some of the new framework that have evolved are not included. The xUnit Framework itself is not mentioned, AutoFixture and all the modern Mock frameworks are missing.
61 reviews
February 16, 2022
I have no compunction about claiming reading credit for having read ~580 pages before throwing in the towel. As others have noted, this book is ~200 pages of great content inside an *800* page package. In addition, large swathes of it have been rendered largely irrelevant due to 1) the sophisticated features of modern programming languages and test frameworks like Jest/Rspec and 2) industry convergence on best practices. There are some good ideas here - the emphasis on the value of testing for speed/quality/documentation and the breakdown of mocks/spies/stubs/doubles in particular - and I’m sure it was ground-breaking for its time, but there is *so* much more content than there needed to be. I’ll save my 800 pagers for Brandon Sanderson!
105 reviews1 follower
November 4, 2019
A bit long and repetitive but very good content. If you are looking to learn about unit testing, there are probably better, more approachable books. However if you need to manage a large amount of tests, then this book is a gem. It is 900 pages so I don't recommend reading straight through as I did, but it would be great for a reference.
Profile Image for Matt McCormick.
45 reviews27 followers
March 9, 2018
Very tough to read through as it's laid out as more of a reference book with many references back and forth to other sections.
4 reviews1 follower
February 22, 2019
Assert awesome

Excellent book. When your code sense already tells you what makes a good test or a bad one, xUnit Test Patterns can explain why.
Profile Image for Luís Soares.
35 reviews17 followers
March 28, 2021
Worth it as a reference in terms of testing patterns and standardization of testing terminology. I'd give a 5 if it was rewritten in 300 pages and not so repetitive.
Profile Image for Edward.
3 reviews1 follower
November 9, 2012
A huge tome on everything xUnit. Part 1, the Narratives, explains all the basics and I would recommend reading completely. It gives a great overview of both the test "smells" and the patterns in later sections. Part 2, the Test Smells I think of as Martin Fowler's Refactoring book, except dealing strictly with testing. It's organized very similarly to that classic book. Part 3, the Patterns, is like Fowler's Patterns of Enterprise Application Architecture, except again, only dealing with common patterns in designing software tests. This last section I have not yet read entirely, but use more as a reference.

A note on the Kindle edition. They did this right. A link for every pattern, smell and glossary term. Very easy to bounce back and forth, which is essential in a reference work like this. This is especially true with the Narratives where some pages contain a dozen or more links to other sections of the book. Very well done.
6 reviews
August 13, 2015
I thought this was a good book, particularly if you're new or somewhat new to automated testing. I was a bit disappointed personally though as I found that what other reviewers have said to be true: the book is about 3x longer than it needs to be.

The book is fairly repetitious. You'll find a chapter discussing a subject. Then there will be a section describing that subject as a pattern. Then each of the variations of that pattern (which were already discussed) are discussed again as separate patterns.

And the patterns are good from a high-level but I was looking for perhaps one more level of detail with more tactical examples. I understand that you can setup test fixtures by re-using data or creating all new data (which may be destroyed at the end of the test or new data is guaranteed to be unique). But I was hoping for more detailed examples about how to setup and organize that kind of data. How do you setup complex fixtures?
June 22, 2012
This book is not meant to be read in its entirety, so I did not. The first 181 pages that I did read gave a nice coverage of unit testing with (surprise surprise) a particular focus on xUnit tools. The book moves along in a logical fashion, each chapter building on the previous ones which I consider to be very important. The contained illustrations I didn't care for too much; mostly I thought they were unnecessary for me personally but I can see that others might benefit more from them.
After the first 181 pages the catalog of smells and patterns begins. This in fact covers most of the book, which is over 700 pages without the appendices. As time goes by and different testing needs emerge, this catalog is a good thing have handy.
Profile Image for Stefan Teixeira.
27 reviews6 followers
July 9, 2015
This book is definitely the "Unit Testing Bible". It's a great reference book and it covers everything you could imagine about unit tests, which is very valuable. Despite its focus on unit testing, much of the smells, patterns and techniques covered by the book are definitely applicable to automated tests in other levels, such as integration or UI.

However, the book is VERY repetitive. If you want to read it in its entirety, be prepared to read the same things all over again for multiple times. I recommend to focus on Part I and in Part II/III just focus on the topics that you want to review.
542 reviews9 followers
March 28, 2016
A great reference book on patterns around testing, not so interesting to read from cover-to-cover. However, when you have a problem with your automated tests, then there is most likely a solution in this book.

Many problems you run into with starting test automation are covered. I wish I had read this book years before and would not have needed to make the errors for myself. If you are testing your software with automated tests, then this book is a must-read. Don’t shy away because it has so many pages. Go on and read part one and the chapters who answer the questions you have at the moment. This will be time well spend and saves you hours of pain.
Profile Image for Jean Tessier.
148 reviews22 followers
April 22, 2016
An amazing text on testing. I read the first 200 pages, the narrative, and skimmed the rest of the catalog of patterns. It does a great job of defining a vocabulary for unit testing and really nails down the terminology. The narrative format really brings the language to life, shows how all the terminology fit together very nicely. A must read for anyone doing unit testing with any of the xUnit frameworks.
Displaying 1 - 30 of 50 reviews

Can't find what you're looking for?

Get help and learn more about the design.