Test-driven development was born in the hands and minds of software developers looking for a way to develop software better and faster. This book was written by one such software developer who wishes to make learning TDD easier. Because most of the problems encountered by developers new to TDD relate to overcoming technical hindrances, we’ve taken an extremely hands-on approach. Not only do we explain TDD through an extended hands-on example, but we also devote several chapters to showing you how to write unit tests for technology that’s generally considered difficult to test. First-hand experiences will be the biggest learning opportunities you’ll encounter, but this book can act as the catalyst that gets you past the steepest learning curve.
This book is aimed at Java programmers of all experience levels who are looking to improve their productivity and the quality of the code they develop. Test-driven development lets you unleash your potential by offering a solid framework for building software reliably in small increments. Regardless of whether you’re creating a missile-control system or putting together the next YouTube, you can benefit from adopting TDD.
Our second intended audience includes Java programmers who aren’t necessarily interested in TDD but who are looking for help in putting their code under test. Test-driven development is primarily a design and development technique; but writing unit tests is such an essential activity in TDD that this book will lend you a hand during pure test-writing, too—we cover a lot of (so-called) difficult-to-test technologies such as data-access code, concurrent programs, and user-interface code.
Whether you’re simply looking to get the job done or have a larger goal of personal improvement in mind, we hope you’ll find this book helpful.
You’re reading a book that covers a lot of ground. In order to structure the material, we’ve divided the book into three parts with distinct focuses. Part 1 introduces the book’s main topics—test-driven development and acceptance test-driven development—starting with the very basics.
Chapter 1 begins with a problem statement—the challenges we need to overcome—and explains how TDD and acceptance TDD provide an effective solution in the form of test-first programming, evolutionary design, test automation, and merciless refactoring.
Chapter 2 gets our hands dirty, extending our understanding of TDD through an in-depth example: a homegrown template engine we test-drive from scratch. Along the way, we discuss how to manage the tests we want to write in a test list and how to select the next test from that list.
Chapter 3 finishes what chapter 2 started, continuing the development of the template engine through an extensive design change, starting with a spike—a learning experiment—and then proceeding to make the change to the template engine in a controlled, disciplined manner.
Chapter 4 brings our perspective back to a higher level to explain the strategies in our toolkit, from selecting tests to making them pass. We also talk about essential testing concepts such as fixtures, test doubles, and the differences between state- and interaction-based testing. After giving some guidelines for creating testable designs, chapter 4 ends with an overview of a number of key test patterns and a section on working in a test-first manner with legacy code.
Part 2 is about getting dirty again, demonstrating through working examples how we can apply TDD when working with a variety of technologies that are sometimes referred to as being “difficult to test-drive.” After part 2, you’ll know that folks who say that don’t know what they’re talking about!
Chapter 5 starts our journey through the trenches of web development. We learn to test-drive request/response-style web layers using plain old Java Servlets and Spring Controllers, and we learn to test-drive the presentation layer built with JavaServer Pages and Apache Velocity templates. The chapter also contrasts these request/response examples with test-driving web applications using a component-based framework, Apache Wicket.
Chapter 6 explains how to test-drive the data-access layer behind our web components. We’ll see examples of test-driving data-access objects based on raw JDBC code, the Spring Framework’s JdbcTemplate API, and the de facto object-relational mapping (ORM) tool, Hibernate. We’ll also discuss how to deal with the database in our unit tests and how to fill in the gaps with integration tests. Finally, we share a few tricks for dealing with the file system.
Chapter 7 takes us to the land of the unknown: nondeterministic behavior. After first examining our options for faking time, we turn our attention to multithreading. We begin with a discussion of what we can and should test for, exploring topics such as thread safety, blocking operations, starting and stopping threads, and asynchronous execution. Our trip to the world of the unpredictable ends with a tour of the new synchronization objects from java.util.concurrent that were introduced in Java 5.
Chapter 8 is about face—the face of Java Swing applications, that is. Again, we begin by figuring out what we should test for when test-driving UI code. Then, we look at three design patterns that make our test-driven lives easier, and we briefly introduce two open source tools—Jemmy and Abbot—for unit-testing Swing components. We finish chapter 8 (and part 2) with an extended example, test-driving the face and behavior for a custom Swing component.
Part 3 is a change of tempo. We move from the concrete world of test-driving objects and classes into the fuzzier world of building whole systems in a test-first manner with acceptance TDD.
Chapter 9 gets us going with an introduction to user stories for managing requirements, and to the essence of acceptance tests. Once we’re up to speed with the what, we focus on the how—the process of acceptance TDD and what it requires from the team. We also crystallize the benefits of and the reasons for developing software with acceptance TDD. The chapter ends with a discussion of what kinds of aspects our acceptance tests should specify about the system we’re building and an overview of some of the tools in our disposal.
Chapter 10 makes acceptance TDD more concrete by taking a closer look at Fit, a popular acceptance-testing tool. Our Fit tutorial begins with a description of how the developer can use Fit to collaborate with the customer, first sketching acceptance tests in a tabular format and then touching them up into syntax recognized by Fit. We then see how to implement the backing code that glues our tabular tests into interaction with the system, first going through the three standard fixtures built into Fit and then looking at additional utilities provided by the FitLibrary, an extension to Fit. Finally, we learn to run our precious Fit tests from the command line and as part of an Apache Ant build.
Chapter 11 expands our perspective by looking at a number of strategies for implementing our acceptance tests independent of the tools in use. After going through our options for connecting tests to the system we’re developing, we discuss the kinds of limitations and opportunities that technology puts in our way. We also share some tips for speeding up acceptance tests and keeping complexity in check.
Chapter 12 ends part 3 as a black sheep of sorts—a chapter on ensuring the success of TDD adoption. We begin by exploring what ingredients should be in place for us to achieve lasting change, both for ourselves and for our peers. We then focus on resistance: how to recognize it and how to deal with it. Finally, we go through a long list of things in our toolbox that can facilitate the successful adoption we’re seeking.
Because writing unit tests is so central to test-driven development, we’ve also provided three brief tutorials on some of the essential tools; you can use them as cheat sheets. Appendices A and B are for the JUnit unit-testing framework, illustrating the syntax for versions 4.3 and 3.8, respectively. Appendix C does the same for EasyMock, a dynamic mock-object framework we can use to generate smart test doubles.
Test-driving code in the comfort of our favorite IDE is cool, but we need to make those tests part of our automated build. That’s why we’ve included appendix D: a brief tutorial for running JUnit tests with Apache Ant, the standard build tool for Java developers.
The code examples presented in this book consist of Java source code as well as a host of markup languages and output listings. We present the longer pieces of code as listings with their own headers. Smaller bits of code are run inline with the text. In all cases, we present the code using a monospaced font, to differentiate it from the rest of the text. In part 2, we frequently refer from the text to elements in code listings. Such references are also presented using a monospaced font, to make them stand out from plain English. Many longer listings also have numbered annotations that we refer to in the text.
The complete example code for the book can be downloaded from the Manning website page for this book, at http://www.manning.com/koskela. This includes the source code shown in the book as well as the omitted parts-everything you need to play and tinker with the code, taking it further from where we left off, or tearing it into pieces for a closer autopsy.
The download includes a Maven 2 POM file and instructions for installing and using Maven (http://maven.apache.org) to compile and run the examples. Note that the download doesn’t include the various dependencies, and you need to have an Internet connection when running the Maven build for the first time—Maven will then download all the required dependencies from the Internet. After that, you’re free to disconnect and play with the examples offline.
The code examples were written against Java 5, so you’ll need to have that installed in order to compile and run the examples. You can download a suitable Java environment from http://java.sun.com/javase. (To compile the code, you’ll need to download the JDK, not the JRE.)
We seriously recommend installing a proper IDE as well. The example code comes in the form of an Eclipse project, so you may want to download and install the latest and greatest version of Eclipse (http://www.eclipse.org). Other mainstream tools such as IntelliJ IDEA (http://www.jetbrains.com/idea) and NetBeans (http://www.netbeans.org) should work fine, too—you’ll just need to configure the project yourself.
There’s one hot topic that we don’t cover in the 12 chapters that made their way into the final manuscript: test-driving Enterprise JavaBeans. Instead, we’ve provided more than 40 pages of detailed advice for developers working with this technology in the form of an extra chapter that’s only available online.
This bonus chapter covers Enterprise JavaBeans, ranging from regular session beans we use to encapsulate our applications’ business logic to the persistence-oriented entity beans to the asynchronous-message-driven beans and the Timer API.
Although we focus on covering the latest and greatest EJB 3.0 specification, we show some key tips and tricks for both 3.0 and the older 2.x API. We do this because many legacy systems continue to use the 2.x version of the EJB specification, regardless of the massive testability and design improvements introduced in the EJB 3.0 specification.
You can download the bonus chapter from http://www.manning.com/koskela.
This book should give you enough ammunition to get going with test-driven development, but there’s bound to be a question or two that we haven’t managed to answer in full. Fortunately, Manning provides an online forum where you can talk to the authors of Manning titles, including the one you’re reading right now. You can reach Lasse at the Author Online forum for Test Driven at http://www.manning-sandbox.com/forum.jspa?forumID=306.
Test-driven development is a technique and a methodology that can’t be described perfectly in a single written document, be it a short article or a series of books. This is partly because TDD is a technique that evolves together with the practitioner and partly because writing tests—a central activity in TDD—varies so much from one technology domain to the next. There are always new twists or tricks that we could’ve included but didn’t. Thus, it’s good to know where to go for further assistance. The testdrivendevelopment Yahoo! group is an excellent resource and frequently features interesting discussions about TDD and related issues. If you have a burning question and aren’t sure who to ask, ask the mailing list!
If tapping into the Yahoo! group isn’t enough to satisfy your need for passive information-gathering about what’s happening in the community, I also suggest subscribing your feed reader to http://www.testdriven.com, a web portal focused on TDD. This portal gives you a heads-up about any relevant new article, blog entry, or development tool that appears on the scene. And, of course, many of the industry conferences on agile methods feature content about or related to TDD, so why not start attending those if you haven’t already?
I’m looking forward to seeing you join the TDD community!
Purchase of Test Driven includes free access to a private web forum run by Manning Publications, where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum and subscribe to it, point your web browser to http://www.manning.com/koskela. This page provides information on how to get on the forum once you are registered, what kind of help is available, and the rules of conduct on the forum.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions, lest his interest stray!
The Author Online forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.