Siêu thị PDFTải ngay đi em, trời tối mất

Thư viện tri thức trực tuyến

Kho tài liệu với 50,000+ tài liệu học thuật

© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Growing object - oriented sofrware, guided by tests
PREMIUM
Số trang
385
Kích thước
4.8 MB
Định dạng
PDF
Lượt xem
1781

Growing object - oriented sofrware, guided by tests

Nội dung xem thử

Mô tả chi tiết

ptg

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Praise for Growing Object-Oriented Software, Guided by Tests

“The authors of this book have led a revolution in the craft of programming by controlling

the environment in which software grows. Their Petri dish is the mock object, and their

microscope is the unit test. This book can show you how these tools introduce a

repeatability to your work that would be the envy of any scientist.”

—Ward Cunningham

“At last a book, suffused with code, that exposes the deep symbiosis between TDD and

OOD. The authors, pioneers in test-driven development, have packed it with principles,

practices, heuristics, and (best of all) anecdotes drawn from their decades of professional

experience. Every software craftsman will want to pore over the chapters of worked

examples and study the advanced testing and design principles. This one’s a keeper.”

—Robert C. Martin

“Design is often discussed in depth, but without empiricism. Testing is often promoted,

but within the narrow definition of quality that relates only to the presence or absence of

defects. Both of these perspectives are valuable, but each on its own offers little more than

the sound of one hand clapping. Steve and Nat bring the two hands together in what

deserves—and can best be described as—applause. With clarity, reason, and humour,

their tour de force reveals a view of design, testing, code, objects, practice, and process

that is compelling, practical, and overflowing with insight.”

—Kevlin Henney, co-author of Pattern-Oriented Software Architecture

and 97 Things Every Programmer Should Know

“Steve and Nat have written a wonderful book that shares their software craftsmanship

with the rest of the world. This is a book that should be studied rather than read, and

those who invest sufficient time and energy into this effort will be rewarded with superior

development skills.”

—David Vydra, publisher, testdriven.com

“This book presents a unique vision of test-driven development. It describes the mature

form of an alternative strain of TDD that sprang up in London in the early 2000s,

characterized by a totally end-to-end approach and a deep emphasis on the messaging

aspect of objects. If you want to be an expert in the state of the art in TDD, you need to

understand the ideas in this book.”

—Michael Feathers

“With this book you’ll learn the rhythms, nuances in thinking, and effective programming

practices for growing tested, well-designed object-oriented applications from the masters.”

—Rebecca Wirfs-Brock

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

This page intentionally left blank

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Growing

Object-Oriented

Software,

Guided

by Tests

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

The Addison-Wesley Signature Series provides readers with

practical and authoritative information on the latest trends in modern

technology for computer professionals. The series is based on one simple

premise: Great books come from great authors. Books in the series are

personally chosen by expert advisors, world-class authors in their own

right. These experts are proud to put their signatures on the covers, and

their signatures ensure that these thought leaders have worked closely

with authors to define topic coverage, book scope, critical content, and

overall uniqueness. The expert signatures also symbolize a promise to

our readers: You are reading a future classic.

Visit informit.com/awss for a complete list of available products.

The Addison-Wesley

Signature Series

Kent Beck, Mike Cohn, and Martin Fowler, Consulting Editors

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Growing

Object-Oriented

Software,

Guided

by Tests

Steve Freeman and Nat Pryce

Upper Saddle River, NJ • Boston • Indianapolis • San Francisco

New York • Toronto • Montreal • London • Munich • Paris • Madrid

Cape Town • Sydney • Tokyo • Singapore • Mexico City

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Many of the designations used by manufacturers and sellers to distinguish their products are claimed

as trademarks. Where those designations appear in this book, and the publisher was aware of a

trademark claim, the designations have been printed with initial capital letters or in all capitals.

The authors and publisher have taken care in the preparation of this book, but make no expressed

or implied warranty of any kind and assume no responsibility for errors or omissions. No liability

is assumed for incidental or consequential damages in connection with or arising out of the use of

the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulk purchases

or special sales, which may include electronic versions and/or custom covers and content particular

to your business, training goals, marketing focus, and branding interests. For more information,

please contact:

U.S. Corporate and Government Sales

(800) 382–3419

[email protected]

For sales outside the United States please contact:

International Sales

[email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data:

Freeman, Steve, 1958-

Growing object-oriented software, guided by tests / Steve Freeman and Nat Pryce.

p. cm.

ISBN 978-0-321-50362-6 (pbk. : alk. paper) 1. Object-oriented programming

(Computer science) 2. Computer software--Testing. I. Pryce, Nat. II. Title.

QA76.64.F747 2010

005.1'17--dc22

2009035239

Copyright © 2010 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected by

copyright, and permission must be obtained from the publisher prior to any prohibited reproduction,

storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical,

photocopying, recording, or likewise. For information regarding permissions, write to:

Pearson Education, Inc

Rights and Contracts Department

501 Boylston Street, Suite 900

Boston, MA 02116

Fax (617) 671 3447

ISBN-13: 978–0–321–50362–6

ISBN-10: 0–321–50362–7

Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.

First printing October 2009

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

To Paola, for all her support; to Philip, who sometimes missed out

—Steve

To Lamaan who put up with me spending time writing this book,

and Oliver Tarek who did not

—Nat

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

This page intentionally left blank

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Contents

Foreword ...................................................................................................... xv

Preface ........................................................................................................ xvii

Acknowledgments ....................................................................................... xxi

About the Authors .................................................................................... xxiii

Part I: Introduction ......................................................................................... 1

Chapter 1: What Is the Point of Test-Driven Development? ..................... 3

Software Development as a Learning Process ..................................... 3

Feedback Is the Fundamental Tool .................................................... 4

Practices That Support Change .......................................................... 5

Test-Driven Development in a Nutshell ............................................. 6

The Bigger Picture ............................................................................. 7

Testing End-to-End ............................................................................ 8

Levels of Testing ................................................................................ 9

External and Internal Quality .......................................................... 10

Chapter 2: Test-Driven Development with Objects ................................ 13

A Web of Objects ............................................................................ 13

Values and Objects .......................................................................... 13

Follow the Messages ........................................................................ 14

Tell, Don’t Ask ................................................................................ 17

But Sometimes Ask .......................................................................... 17

Unit-Testing the Collaborating Objects ........................................... 18

Support for TDD with Mock Objects .............................................. 19

ix

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Chapter 3: An Introduction to the Tools ................................................ 21

Stop Me If You’ve Heard This One Before ...................................... 21

A Minimal Introduction to JUnit 4 .................................................. 21

Hamcrest Matchers and assertThat() ............................................... 24

jMock2: Mock Objects .................................................................... 25

Part II: The Process of Test-Driven Development ......................................... 29

Chapter 4: Kick-Starting the Test-Driven Cycle ..................................... 31

Introduction .................................................................................... 31

First, Test a Walking Skeleton ......................................................... 32

Deciding the Shape of the Walking Skeleton .................................... 33

Build Sources of Feedback ............................................................... 35

Expose Uncertainty Early ................................................................ 36

Chapter 5: Maintaining the Test-Driven Cycle ....................................... 39

Introduction .................................................................................... 39

Start Each Feature with an Acceptance Test .................................... 39

40

Separate Tests That Measure Progress from Those That Catch

Regressions ......................................................................................

Start Testing with the Simplest Success Case .................................... 41

Write the Test That You’d Want to Read ........................................ 42

Watch the Test Fail .......................................................................... 42

Develop from the Inputs to the Outputs .......................................... 43

Unit-Test Behavior, Not Methods .................................................... 43

Listen to the Tests ............................................................................ 44

Tuning the Cycle ............................................................................. 45

Chapter 6: Object-Oriented Style ........................................................... 47

Introduction .................................................................................... 47

Designing for Maintainability .......................................................... 47

Internals vs. Peers ............................................................................ 50

No And’s, Or’s, or But’s .................................................................. 51

Object Peer Stereotypes ................................................................... 52

Composite Simpler Than the Sum of Its Parts .................................. 53

Context Independence ..................................................................... 54

Hiding the Right Information .......................................................... 55

An Opinionated View ...................................................................... 56

Chapter 7: Achieving Object-Oriented Design ....................................... 57

How Writing a Test First Helps the Design ..................................... 57

Communication over Classification ................................................. 58

x Contents

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Value Types ..................................................................................... 59

Where Do Objects Come From? ...................................................... 60

Identify Relationships with Interfaces .............................................. 63

Refactor Interfaces Too ................................................................... 63

Compose Objects to Describe System Behavior ............................... 64

Building Up to Higher-Level Programming ...................................... 65

And What about Classes? ................................................................ 67

Chapter 8: Building on Third-Party Code .............................................. 69

Introduction .................................................................................... 69

Only Mock Types That You Own ................................................... 69

Mock Application Objects in Integration Tests ................................ 71

Part III: A Worked Example ......................................................................... 73

Chapter 9: Commissioning an Auction Sniper ........................................ 75

To Begin at the Beginning ................................................................ 75

Communicating with an Auction ..................................................... 78

Getting There Safely ........................................................................ 79

This Isn’t Real ................................................................................. 81

Chapter 10: The Walking Skeleton ........................................................ 83

Get the Skeleton out of the Closet ................................................... 83

Our Very First Test .......................................................................... 84

Some Initial Choices ........................................................................ 86

Chapter 11: Passing the First Test .......................................................... 89

Building the Test Rig ....................................................................... 89

Failing and Passing the Test ............................................................. 95

The Necessary Minimum ...............................................................102

Chapter 12: Getting Ready to Bid ........................................................105

An Introduction to the Market ......................................................105

A Test for Bidding .........................................................................106

The AuctionMessageTranslator .....................................................112

Unpacking a Price Message ............................................................118

Finish the Job .................................................................................121

Chapter 13: The Sniper Makes a Bid ...................................................123

Introducing AuctionSniper .............................................................123

Sending a Bid .................................................................................126

Tidying Up the Implementation .....................................................131

Contents xi

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Defer Decisions ..............................................................................136

Emergent Design ............................................................................137

Chapter 14: The Sniper Wins the Auction ............................................139

First, a Failing Test ........................................................................139

Who Knows about Bidders? ...........................................................140

The Sniper Has More to Say ..........................................................143

The Sniper Acquires Some State .....................................................144

The Sniper Wins ............................................................................146

Making Steady Progress .................................................................148

Chapter 15: Towards a Real User Interface .........................................149

A More Realistic Implementation ..................................................149

Displaying Price Details .................................................................152

Simplifying Sniper Events ...............................................................159

Follow Through .............................................................................164

Final Polish ....................................................................................168

Observations ..................................................................................171

Chapter 16: Sniping for Multiple Items ................................................175

Testing for Multiple Items .............................................................175

Adding Items through the User Interface ........................................183

Observations ..................................................................................189

Chapter 17: Teasing Apart Main .........................................................191

Finding a Role ...............................................................................191

Extracting the Chat ........................................................................192

Extracting the Connection .............................................................195

Extracting the SnipersTableModel .................................................197

Observations ..................................................................................201

Chapter 18: Filling In the Details .........................................................205

A More Useful Application ............................................................205

Stop When We’ve Had Enough ......................................................205

Observations ..................................................................................212

Chapter 19: Handling Failure ...............................................................215

What If It Doesn’t Work? ..............................................................215

Detecting the Failure ......................................................................217

Displaying the Failure ....................................................................218

Disconnecting the Sniper ................................................................219

Recording the Failure .....................................................................221

Observations ..................................................................................225

xii Contents

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Part IV: Sustainable Test-Driven Development ...........................................227

Chapter 20: Listening to the Tests ........................................................229

Introduction ...................................................................................229

I Need to Mock an Object I Can’t Replace (without Magic) ..........230

Logging Is a Feature .......................................................................233

Mocking Concrete Classes .............................................................235

Don’t Mock Values ........................................................................237

Bloated Constructor .......................................................................238

Confused Object ............................................................................240

Too Many Dependencies ...............................................................241

Too Many Expectations .................................................................242

What the Tests Will Tell Us (If We’re Listening) ............................244

Chapter 21: Test Readability ...............................................................247

Introduction ...................................................................................247

Test Names Describe Features .......................................................248

Canonical Test Structure ................................................................251

Streamline the Test Code ...............................................................252

Assertions and Expectations ..........................................................254

Literals and Variables ....................................................................255

Chapter 22: Constructing Complex Test Data .....................................257

Introduction ...................................................................................257

Test Data Builders .........................................................................258

Creating Similar Objects ................................................................259

Combining Builders .......................................................................261

Emphasizing the Domain Model with Factory Methods ................261

Removing Duplication at the Point of Use .....................................262

Communication First .....................................................................264

Chapter 23: Test Diagnostics ...............................................................267

Design to Fail .................................................................................267

Small, Focused, Well-Named Tests ................................................268

Explanatory Assertion Messages ....................................................268

Highlight Detail with Matchers .....................................................268

Self-Describing Value .....................................................................269

Obviously Canned Value ...............................................................270

Tracer Object .................................................................................270

Explicitly Assert That Expectations Were Satisfied ........................271

Diagnostics Are a First-Class Feature .............................................271

Contents xiii

From the Library of Lee Bogdanoff

www.it-ebooks.info

ptg

Chapter 24: Test Flexibility ..................................................................273

Introduction ...................................................................................273

Test for Information, Not Representation ......................................274

Precise Assertions ...........................................................................275

Precise Expectations .......................................................................277

“Guinea Pig” Objects ....................................................................284

Part V: Advanced Topics ............................................................................287

Chapter 25: Testing Persistence ............................................................289

Introduction ...................................................................................289

Isolate Tests That Affect Persistent State ........................................290

Make Tests Transaction Boundaries Explicit .................................292

Testing an Object That Performs Persistence Operations ...............294

Testing That Objects Can Be Persisted ...........................................297

But Database Tests Are S-l-o-w! ....................................................300

Chapter 26: Unit Testing and Threads .................................................301

Introduction ...................................................................................301

Separating Functionality and Concurrency Policy ..........................302

Unit-Testing Synchronization .........................................................306

Stress-Testing Passive Objects ........................................................311

Synchronizing the Test Thread with Background Threads .............312

The Limitations of Unit Stress Tests ...............................................313

Chapter 27: Testing Asynchronous Code .............................................315

Introduction ...................................................................................315

Sampling or Listening ....................................................................316

Two Implementations ....................................................................318

Runaway Tests ..............................................................................322

Lost Updates ..................................................................................323

Testing That an Action Has No Effect ...........................................325

Distinguish Synchronizations and Assertions .................................326

Externalize Event Sources ..............................................................326

Afterword: A Brief History of Mock Objects ..............................................329

Appendix A: jMock2 Cheat Sheet ...............................................................335

Appendix B: Writing a Hamcrest Matcher .................................................343

Bibliography ...............................................................................................347

Index ..........................................................................................................349

xiv Contents

From the Library of Lee Bogdanoff

www.it-ebooks.info

Tải ngay đi em, còn do dự, trời tối mất!