Book Image

Testing with JUnit

By : Leonard Przybylski, Frank Appel
Book Image

Testing with JUnit

By: Leonard Przybylski, Frank Appel

Overview of this book

Table of Contents (16 chapters)
Testing with JUnit
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Preface

Testing with JUnit is a skill that presents much harder challenges than you might expect at first sight. This is because, despite its temptingly simple API, the tool plays ball with profound and well-conceived concepts. Hence, it's important to acquire a deep understanding of the underlying principles and practices. This avoids ending up in gridlocked development due to messed-up production and testing code.

Mastering high-quality software development driven by unit tests is about following well-attuned patterns and methods as a matter of routine rather, than reinventing the wheel on a daily basis. If you have a good perception of the conceptual requirements and a wide-ranging arsenal of solution approaches, they will empower you to continuously deliver code, which achieves excellent ratings with respect to the usual quality metrics out of the box.

To impart these capabilities, this book provides you with a well-thought-out, step-by-step tutorial. Foundations and essential techniques are elaborated, guided by a golden thread along the development demands of a practically relevant sample application. The chapters and sections are built on one another, each starting with in-depth considerations about the current topic's problem domain and concluding with an introduction to and discussion of the available solution strategies.

At the same time, it's taken care that all thoughts are backed up by illustrative images and expressive listings supplemented by adequate walkthroughs. For the best possible understanding, the complete source code of the book's example app is hosted at https://github.com/fappel/Testing-with-JUnit. This allows you to comprehend the various aspects of JUnit testing from within a more complex development context and facilitates an exchange of ideas using the repository's issue tracker.

What this book covers

Chapter 1, Getting Started, opens with a motivational section about the benefits of JUnit testing and warms up with a short coverage of the toolchain used throughout the book. After these preliminaries, the example project is kicked off, and writing the first unit test offers the opportunity to introduce the basics of the test-driven development paradigm.

Chapter 2, Writing Well-structured Tests, explains why the four fundamental phases' test pattern is perfectly suited to test a unit's behavior. It elaborates on several fixture initialization strategies, shows how to deduce what to test, and concludes by elucidating different test-naming conventions.

Chapter 3, Developing Independently Testable Units, shows you how to decompose big requirements into small and separately testable components and illustrates the impact of collaboration dependencies on testing efforts. It explains the importance of test isolation and demonstrates the use of test doubles to achieve it.

Chapter 4, Testing Exceptional Flow, discusses the pros and cons of various exception capture and verification techniques. Additionally, it explains the meaning of the fail fast strategy and outlines how it intertwines with tests on particular boundary conditions.

Chapter 5, Using Runners for Particular Testing Purposes, presents JUnit's pluggable test processor architecture that allows us to adjust test execution to highly diverse demands. It covers how to write custom runners and introduces several useful areas of application.

Chapter 6, Reducing Boilerplate with JUnit Rules, unveils the test interception mechanism behind the rule concept, which allows you to provide powerful, test-related helper classes. After deepening the knowledge by writing a sample extension, the chapter continues with the tools' built-in utilities and concludes by inspecting useful third-party vendor offerings.

Chapter 7, Improving Readability with Custom Assertions, teaches the writing of concise verifications that reveal the expected outcome of a test clearly. It shows how domain-specific assertions help you to improve readability and discusses the assets and drawbacks of the built-in mechanisms, Hamcrest and AssertJ.

Chapter 8, Running Tests Automatically within a CI Build, concludes the example project with important considerations of test-related architectural aspects. Finally, it rounds out the book by giving an introduction to continuous integration, which is an excellent brief of the test first approach and establishes short feedback cycles efficiently by automation.

Appendix, References, lists all the bibliographic references used throughout the chapters of this book.

What you need for this book

For better understanding and deepening of the knowledge acquired, it's advisable to comprehend the examples within a local workspace on your computer. As JUnit is written in Java, the most important thing you need is Java Development Kit. The sample code requires at least Java 8, which can be downloaded from http://www.oracle.com/technetwork/java/index.html.

Although it's possible to compile and run the listings from the command line, the book assumes you're working with a Java IDE, such as Eclipse (http://www.eclipse.org/), IntelliJ IDEA (https://www.jetbrains.com/idea/) or NetBeans (https://netbeans.org/). The sample application was developed using Eclipse and so are the screenshots.

As mentioned in the preceding paragraph, the book's code sources are hosted at GitHub, so you can clone your local copy using Git (https://git-scm.com/). The chapter and sample app projects are based on Maven (https://maven.apache.org/) with respect to their structure and dependency management, which makes it easy to get the sample solutions up and running. This allows a thorough live inspection and debugging of passages that are not fully understood.

Due to this availability of comprehensive sources, the listings in the chapters are stripped down using static imports wherever appropriate or use ellipses to denote a class that has content unrelated to the topic. This helps you to keep the snippets small and focus on the important stuff.

Apart from that, in the course of the book, several Java libraries are introduced. They can all be declared as Maven dependencies and can be downloaded automatically from the publicly available Maven Central Repository (http://search.maven.org/). For some examples, you can refer to the pom.xml files of the sample application. An overview of the testing toolset is given in Chapter 1, Getting Started.

Who this book is for

No matter what your specific background as a Java developer is, whether you're simply interested in building up a safety net to reduce the regression of your desktop application or in improving your server-side reliability based on robust and reusable components, unit testing is the way to go. This book provides you with a comprehensive, but concise, entrance, advancing your knowledge step-wise, to a professional level.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "As a result, a test case was a compound of various methods called testFoo, testBar, and so on."

A block of code is set as follows:

private final static int NEW_FETCH_COUNT
  = Timeline.DEFAULT_FETCH_COUNT + 1;

@Test
public void setFetchCount() {
  // (1) setup (arrange, build)
  Timeline timeline = new Timeline();

  // (2) exercise (act, operate)
  timeline.setFetchCount( NEW_FETCH_COUNT );

  // (3) verify (assert, check)
  assertEquals( NEW_FETCH_COUNT, timeline.getFetchCount() );
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

private ItemProvider itemProvider;
private Timeline timeline;

@Before
public void setUp() {
  itemProvider = ???
  timeline = new Timeline( itemProvider );
}

Any command-line input or output is written as follows:

mvn clean test

New terms and important words are shown in bold like this: "Changing code without changing its behavior is called refactoring."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail , and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: https://www.packtpub.com/sites/default/files/downloads/6603OS_Graphics.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at , and we will do our best to address the problem.