Testing with JUnit
By Frank Appel
()
About this ebook
Master high quality software development driven by unit tests
About This Book- Design and implement robust system components by means of the de facto unit testing standard in Java
- Reduce defect rate and maintenance effort, plus simultaneously increase code quality and development pace
- Follow a step-by-step tutorial imparting the essential techniques based on real-world scenarios and code walkthroughs
No matter what your specific background as a Java developer, whether you're simply interested in building up a safety net to reduce regressions 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.
What You Will Learn- Organize your test infrastructure and resources reasonably
- Understand and write well structured tests
- Decompose your requirements into small and independently testable units
- Increase your testing efficiency with on-the-fly generated stand-in components and deal with the particularities of exceptional flow
- Employ runners to adjust to specific test demands
- Use rules to increase testing safety and reduce boilerplate
- Use third party supplements to improve the expressiveness of your verification statements
JUnit has matured to become the most important tool when it comes to automated developer tests in Java. Supported by all IDEs and build systems, it empowers programmers to deliver software features reliably and efficiently. However, writing good unit tests is a skill that needs to be learned; otherwise it's all too easy to end up in gridlocked development due to messed up production and testing code. Acquiring the best practices for unit testing will help you to prevent such problems and lead your projects to success with respect to quality and costs.
This book explains JUnit concepts and best practices applied to the test first approach, a foundation for high quality Java components delivered in time and budget.
From the beginning you'll be guided continuously through a practically relevant example and pick up background knowledge and development techniques step by step. Starting with the basics of tests organization you'll soon comprehend the necessity of well structured tests and delve into the relationship of requirement decomposition and the many-faceted world of test double usage. In conjunction with third-party tools you'll be trained in writing your tests efficiently, adapt your test case environment to particular demands and increase the expressiveness of your verification statements. Finally, you'll experience continuous integration as the perfect complement to support short feedback cycles and quality related reports for your whole team.
The tutorial gives a profound entry point in the essentials of unit testing with JUnit and prepares you for test-related daily work challenges.
Style and approachThis is an intelligible tutorial based on an ongoing and non-trivial development example. Profound introductions of concepts and techniques are provided stepwise as the programming challenges evolve. This allows you to reproduce and practice the individual skills thoroughly.
Frank Appel
Frank Appel is a stalwart of agile methods and test-driven development in particular. He has over 2 decades of experience as a freelancer and understands software development as a type of craftsmanship. Having adopted the test first approach over a decade ago, he applies unit testing to all kinds of Java-based systems and arbitrary team constellations. He serves as a mentor, provides training, and blogs about these topics at codeaffine.com.
Related to Testing with JUnit
Related ebooks
Mastering Unit Testing Using Mockito and JUnit Rating: 0 out of 5 stars0 ratingsPerformance Testing with JMeter 2.9 Rating: 0 out of 5 stars0 ratingsMockito Essentials Rating: 3 out of 5 stars3/5Building a RESTful Web Service with Spring Rating: 5 out of 5 stars5/5RESTful Java Web Services Security Rating: 0 out of 5 stars0 ratingsIntelliJ IDEA Essentials Rating: 0 out of 5 stars0 ratingsJasmine JavaScript Testing - Second Edition Rating: 0 out of 5 stars0 ratingsMastering Hibernate Rating: 0 out of 5 stars0 ratingsTest-Driven JavaScript Development Rating: 0 out of 5 stars0 ratingsPractical DevOps Rating: 3 out of 5 stars3/5Git Best Practices Guide Rating: 0 out of 5 stars0 ratingsPerformance Testing with JMeter - Second Edition Rating: 0 out of 5 stars0 ratingsTest-Driven Java Development Rating: 4 out of 5 stars4/5Java and Java EE Interview Preparations Rating: 0 out of 5 stars0 ratingsLearning Reactive Programming with Java 8 Rating: 0 out of 5 stars0 ratingsJava 9 Concurrency Cookbook - Second Edition Rating: 0 out of 5 stars0 ratingsJava Persistence with Hibernate Rating: 4 out of 5 stars4/5Java Coding Problems: Improve your Java Programming skills by solving real-world coding challenges Rating: 0 out of 5 stars0 ratingsSpring Security 3.x Cookbook Rating: 0 out of 5 stars0 ratingsPractical Java 8: Lambdas, Streams and new resources Rating: 5 out of 5 stars5/5JUnit Recipes: Practical Methods for Programmer Testing Rating: 4 out of 5 stars4/5Selenium Framework Design in Keyword-Driven Testing: Automate Your Test Using Selenium and Appium Rating: 0 out of 5 stars0 ratingsLearn Selenium in 24 Hours Rating: 0 out of 5 stars0 ratingsSpring Essentials Rating: 0 out of 5 stars0 ratingsThe Java Workshop: Learn object-oriented programming and kickstart your career in software development Rating: 0 out of 5 stars0 ratingsDistributed Computing in Java 9 Rating: 0 out of 5 stars0 ratingsLearning Java Functional Programming Rating: 0 out of 5 stars0 ratings
Programming For You
SQL Guide for Microsoft Access: SQL Basics, Fundamental & Queries Exercise Rating: 5 out of 5 stars5/5Web Designer's Idea Book, Volume 4: Inspiration from the Best Web Design Trends, Themes and Styles Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsPython: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Hacking: Ultimate Beginner's Guide for Computer Hacking in 2018 and Beyond: Hacking in 2018, #1 Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5Minecraft Basics For Dummies Rating: 0 out of 5 stars0 ratingsGame Development with Unreal Engine 5: Learn the Basics of Game Development in Unreal Engine 5 (English Edition) Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython Projects for Beginners: A Ten-Week Bootcamp Approach to Python Programming Rating: 0 out of 5 stars0 ratingsLearn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5
Reviews for Testing with JUnit
0 ratings0 reviews
Book preview
Testing with JUnit - Frank Appel
Table of Contents
Testing with JUnit
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started
Why you should busy yourself with unit tests
Reducing the defect rate
Improving the code quality
Increasing the development pace
Enhancing the specification density
Boosting confidence and courage
Setting the table
Choosing the ingredients
Organizing your code
Serving the starter
Introducing the example app
Understanding the nature of a unit test
Writing the first test
Evaluating test results
Writing tests first
Summary
2. Writing Well-structured Tests
The four phases of a unit test
Using a common test structure
Setting up the fixture
What goes up must come down
Verification
Choosing the next functionality to test
Start with the happy path
Conclude with corner cases
After the war
Getting the test names right
Test prefix
Behavior-expressing patterns
Reducing names to the essentials
Summary
3. Developing Independently Testable Units
Decomposing requirements
Separating concerns
Component dependencies
Understanding isolation
Delegating responsibilities to DOCs
Indirect input and output
Unit isolation with test doubles
Working with test doubles
Placeholder dummies
Fake it till you make it
Providing indirect input with stubs
Recording interactions with spies
Verifying behavior with mocks
Increasing efficiency with mock frameworks
The promised land?
Basic stubbing
Indirect output verification
Using test helpers
Motivation
The test helper class
The test helper object
Summary
4. Testing Exceptional Flow
Testing patterns
Using the fail statement
Annotated expectations
Verification with the ExpectedException rule
Capturing exceptions with closures
Treating collaborators
Fail fast
The stubbing of exceptional behavior
Summary
5. Using Runners for Particular Testing Purposes
Understanding the architecture
What are runners good for?
Looking at the big picture
Writing your own extension
Using custom runners
Furnishing a suite with test cases
Structuring suites into categories
Populating suites automatically
How about creating test doubles with annotations?
Writing dataset tests
Using parameterized tests
Reducing glue code with JUnitParams
Increasing the expressiveness of test descriptions with Burst
Summary
6. Reducing Boilerplate with JUnit Rules
Understanding rules
What are JUnit rules?
Writing your own rule
Configuring the fixture with annotations
Working with advanced concepts
Using ClassRules
The ordering of rule execution
Employing custom solutions
Working with system settings
Ignoring tests conditionally
Summary
7. Improving Readability with Custom Assertions
Working with the JUnit built-in assert approach
Understanding the basics
Reviewing the file session storage
Verifying the storage behavior
Improving readability with assertion helpers
Creating flexible expressions of intent with Hamcrest
Using matcher expressions
Writing custom matchers
Writing fluently readable assertions with AssertJ
Employing assertion chains
Creating your own asserts
Summary
8. Running Tests Automatically within a CI Build
Wrapping up the sample application
Refining the architecture
Separating concerns into modules
Setting up an automated CI build
What is continuous integration?
Principles and practices
Creating your own build
Integrating code coverage reports
Enlarging on code coverage
Automating reporting
Summary
A. References
Chapter 1
Chapter 2
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Index
Testing with JUnit
Testing with JUnit
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2015
Production reference: 1240815
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-660-3
www.packtpub.com
Credits
Author
Frank Appel
Reviewers
Stefan Birkner
Jose Muanis Castro
John Piasetzki
Acquisition Editor
Sonali Vernekar
Content Development Editor
Merwyn D'souza
Technical Editor
Humera Shaikh
Copy Editors
Sarang Chari
Sonia Mathur
Project Coordinator
Nikhil Nair
Proofreader
Safis Editing
Indexer
Monica Ajmera Mehta
Graphics
Jason Monteiro
Production Coordinator
Nilesh R. Mohite
Cover Work
Nilesh R. Mohite
About the Author
Frank Appel is a stalwart of agile methods and test-driven development in particular. He has over 2 decades of experience as a freelancer and understands software development as a type of craftsmanship. Having adopted the test first approach over a decade ago, he applies unit testing to all kinds of Java-based systems and arbitrary team constellations. He serves as a mentor, provides training, and blogs about these topics at codeaffine.com.
I'd like to thank the reviewers, John Piasetzki, Stefan Birkner, and Jose Muanis Castro, and the editors, Sonali Vernekar, Merwyn D'souza, and Humera Shaikh, who spent time and effort to point out my errors, omissions, and sometimes unintelligible writing. In particular, I would like to thank my friend Holger Staudacher, who helped in the reviewing process of the book.
Thanks to all of you for your valuable input and support!
About the Reviewers
Stefan Birkner has a passion for software development. He has a strong preference for beautiful code, tests, and deployment automation. Stefan is a contributor to JUnit and maintains a few other libraries.
Jose Muanis Castro holds a degree in information systems. Originally from the sunny Rio de Janeiro, he now lives in Brooklyn with his wife and kids. At The New York Times, he works with recommendation systems on the personalization team. Previously, he worked on CMS and publishing platforms at Globo.com in Brazil.
Jose is a seasoned engineer with hands-on experience in several languages. He's passionate about continuous improvement, agile methods, and lean processes. With a lot of experience in automation, from testing to deploying, he constantly switches hats between development and operations. When he's not coding, he enjoys riding around on his bike. He was a reviewer on the 2014 book, Mastering Unit Testing Using Mockito and JUnit, Packt Publishing. His Twitter handle is @muanis.
I'm thankful to my wife, Márcia, and my kids, Vitoria and Rafael, for understanding that I couldn't be there sometimes when I was reviewing this book.
John Piasetzki has over 15 years of professional experience as a software developer. He started out doing programming jobs when he was young and obtained a bachelor of science degree in computer engineering. John was fortunate enough to get his start in programming by contributing to WordPress. He continued by working at IBM on WebSphere while getting his degree. Since then, he has moved on to smaller projects. John has worked with technologies such as Python, Ruby, and most recently, AngularJS. He's currently working as a software developer at OANDA, a foreign exchange company.
www.PacktPub.com
Support files, eBooks, discount offers, and more
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
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