Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Mastering Unit Testing Using Mockito and JUnit
Mastering Unit Testing Using Mockito and JUnit
Mastering Unit Testing Using Mockito and JUnit
Ebook604 pages4 hours

Mastering Unit Testing Using Mockito and JUnit

Rating: 0 out of 5 stars

()

Read preview

About this ebook

A practical and easy-to-follow, yet comprehensive, guide to learning advanced JUnit testing. Each topic is explained and placed in context, and for the more inquisitive, there are more details of the concepts used. This book is for you if you are a developer with some experience in Java application development as well as a basic knowledge of JUnit testing. But for those whose skill set is void of any prior experience with JUnit testing, the book also covers basic fundamentals to get you acquainted with the concepts before putting them into practise.
LanguageEnglish
Release dateJul 15, 2014
ISBN9781783982516
Mastering Unit Testing Using Mockito and JUnit

Related to Mastering Unit Testing Using Mockito and JUnit

Related ebooks

Software Development & Engineering For You

View More

Related articles

Reviews for Mastering Unit Testing Using Mockito and JUnit

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering Unit Testing Using Mockito and JUnit - Sujoy Acharya

    Table of Contents

    Mastering Unit Testing Using Mockito and 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

    Errata

    Piracy

    Questions

    1. JUnit 4 – a Total Recall

    Defining unit testing

    Working with JUnit 4

    Setting up Eclipse

    Running the first unit test

    Exploring annotations

    Verifying test conditions with Assertion

    Working with exception handling

    Exploring the @RunWith annotation

    Working with JUnit 4++

    Ignoring a test

    Executing tests in order

    Learning assumptions

    Exploring the test suite

    Asserting with assertThat

    Comparing matchers – equalTo, is, and not

    Working with compound value matchers – either, both, anyOf, allOf, and not

    Working with collection matchers – hasItem and hasItems

    Exploring string matchers – startsWith, endsWith, and containsString

    Exploring built-in matchers

    Building a custom matcher

    Creating parameterized tests

    Working with parameterized constructors

    Working with parameterized methods

    Giving a name

    Working with timeouts

    Exploring JUnit theories

    Externalizing data using @ParametersSuppliedBy and ParameterSupplier

    Dealing with JUnit rules

    Playing with the timeout rule

    Working with the ExpectedException rule

    Unfolding the TemporaryFolder rule

    Exploring the ErrorCollector rule

    Working with the Verifier rule

    Learning the TestWatcher rule

    Working with the TestName rule

    Handling external resources

    Exploring JUnit categories

    Summary

    2. Automating JUnit Tests

    Continuous Integration

    Benefits of CI

    Gradle automation

    Getting started

    Gradling

    Ordering subtasks using doFirst and doLast

    Default tasks

    The task dependency

    Daemon

    Gradle plugins

    The Eclipse plugin

    The Java plugin

    Maven project management

    Installation

    The Archetype plugin

    The Project Object Model (POM) file

    Project dependency

    The build life cycle

    Compiling the project

    Testing the project

    Packaging the project

    The clean life cycle

    The site life cycle

    Another neat tool (Ant)

    Jenkins

    The Gradle project

    The Maven project

    Building the Ant project

    Summary

    3. Test Doubles

    Dummy

    Stub

    Fake

    Mock

    Spy

    Summary

    4. Progressive Mockito

    Working with Mockito

    Why should you use Mockito?

    Qualities of unit testing

    Drinking Mockito

    Configuring Mockito

    Mocking in action

    Mocking objects

    Stubbing methods

    Verifying the method invocation

    Why do we use verify?

    Verifying in depth

    Verifying zero and no more interactions

    Using argument matcher

    Why do we need wildcard matchers?

    The ArgumentMatcher class

    Throwing exceptions

    Stubbing consecutive calls

    Stubbing with an Answer

    Spying objects

    Stubbing void methods

    Capturing arguments with ArgumentCaptor

    Verifying the invocation order

    Changing the default settings

    Resetting mock objects

    Exploring Mockito annotations

    Working with inline stubbing

    Determining mocking details

    Behavior-driven development with Mockito

    Writing tests in BDD style

    The BDD syntax

    Summary

    5. Exploring Code Coverage

    Understanding code coverage

    Learning the inner details of code instrumentation

    Configuring the Eclipse plugin

    Uncovering the Clover plugin

    Working with the EclEmma plugin

    Examining the eCobertura plugin

    Measuring coverage using Gradle

    Working with the Maven Cobertura plugin

    Running the Cobertura Ant task

    Summary

    6. Revealing Code Quality

    Understanding the static code analysis

    Working with the Checkstyle plugin

    Exploring the FindBugs plugin

    Working with the PMD plugin

    Monitoring code quality with SonarQube

    Running SonarQube

    Analyzing code with the SonarQube runner

    Improving quality with the Sonar Eclipse plugin

    Monitoring quality with Gradle and SonarQube

    Monitoring quality with Maven and SonarQube

    Monitoring quality with Ant and SonarQube

    Getting familiar with false positives

    Summary

    7. Unit Testing the Web Tier

    Unit testing servlets

    Building and unit testing a J2EE web application

    Playing with Spring MVC

    Summary

    8. Playing with Data

    Separating concerns

    Unit testing the persistence logic

    Simplifying persistence with Spring

    Verifying the system integrity

    Writing integration tests with Spring

    Summary

    9. Solving Test Puzzles

    Working with the legacy code

    Working with testing impediments

    Designing for testability

    Identifying constructor issues

    Realizing initialization issues

    Working with private methods

    Working with final methods

    Exploring static method issues

    Working with final classes

    Learning the new attribute

    Exploring static variables and blocks

    Working with greenfield code

    Summary

    10. Best Practices

    Writing meaningful tests

    Improving readability

    Breaking everything that could possibly break

    Ignoring simple test cases

    Verifying invalid parameters

    Relying on direct testing

    Staying away from debugging

    Avoiding generic matchers

    Keeping away from @ignore

    Eluding debug messages

    Automating JUnit tests

    Configuring tests

    Running in-memory tests

    Staying away from Thread.sleep

    Keeping unit tests away from the production code

    Avoiding static variables

    Assuming the test execution order

    Loading data from files

    Invoking super.setUp() and super.tearDown()

    Staying away from side effects

    Working with locales

    Working with dates

    Working with assertions

    Using the correct assertion

    Maintaining the assertEquals parameter order

    Striving for one assertion per test

    Handling exceptions

    Working with test smells

    Refactoring duplicates

    Refactoring the test control logic

    Removing the test logic from the production code

    Refactoring over engineered tests

    Summary

    Index

    Mastering Unit Testing Using Mockito and JUnit


    Mastering Unit Testing Using Mockito and JUnit

    Copyright © 2014 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: July 2014

    Production reference: 1080714

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78398-250-9

    www.packtpub.com

    Credits

    Author

    Sujoy Acharya

    Reviewers

    Jose Muanis Castro

    Alexey Grigorev

    Daniel Pacak

    Commissioning Editor

    Amarabha Banerjee

    Acquisition Editor

    Meeta Rajani

    Content Development Editor

    Balaji Naidu

    Technical Editors

    Neha Mankare

    Edwin Moses

    Copy Editor

    Mradula Hegde

    Project Coordinator

    Leena Purkait

    Proofreaders

    Simran Bhogal

    Maria Gould

    Ameesha Green

    Indexer

    Rekha Nair

    Graphics

    Abhinash Sahu

    Production Coordinator

    Melwyn D'sa

    Cover Work

    Melwyn D'sa

    Cover Image

    Disha Haria

    About the Author

    Sujoy Acharya works as a software architect with Siemens Technology and Services Pvt Ltd. (STS). He grew up in a joint family and pursued his graduation in Computer Science and Engineering. His hobbies are watching movies and sitcoms, playing outdoor sports, and reading books.

    He likes to research upcoming technologies. His major contributions are in the fields of Java, J2EE, SOA, Ajax, GWT, and the Spring framework.

    He has authored Test-Driven Development with Mockito, Packt Publishing. He designs and develops healthcare software products. He has over 10 years of industrial experience and has architected and implemented large-scale enterprise solutions.

    I would like to thank my wife, Sunanda, for her patience and endless support in spending many hours reviewing my draft and providing valuable inputs.

    I would also like to thank my mother and late father for their support, blessings, and encouragement.

    To my one-year-old kid, Abhigyan, I am sorry I couldn't be around with you as much as we all wanted, and often, I had to get you away from the laptop. I love you very much.

    About the Reviewers

    Jose Muanis Castro holds an Information Systems degree. Originally from Rio de Janeiro, he now lives in Brooklyn with his wife and kids. He is a software engineer at The New York Times, where he works with recommendation systems on the personalization team. Previously, he worked on the CMS and publishing platforms at Globo.com, the biggest media portal of Brazil.

    He is a seasoned engineer with a history of hands-on experience in several languages. He's passionate about continuous improvement in Agile and Lean processes. With years of experience in automation, right from testing to deploying, he constantly switches hats between development and operations. When he's not coding, he enjoys riding his bike around. 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 at times with them while I was helping to review this book.

    Alexey Grigorev is an experienced software developer with several years of professional Java programming. From the beginning, he successfully adopted the best practices in Extreme Programming (XP), one of which is testing, and drove his teammates to use it. In many cases, he witnessed testing save projects when under constantly developing requirements his team managed to quickly deliver the changes.

    Right now, he is a freelancer who specializes in machine learning and data mining, and he also successfully adopts TDD and testing in these fields to ensure the reliability of his applications.

    For any questions, you can contact him via <alexey.s.grigoriev@gmail.com>.

    Daniel Pacak is a self-made software engineer who fell in love with coding during his studies of Nuclear Physics at Warsaw University of Technology. This was back in 2006 when no one cared about unit testing at all. He acquired his professional experience by working on several business-critical projects, mainly web applications, for clients in financial services, telecommunications, e-commerce, and the travel industry.

    When he's not coding, he enjoys lifting weights in the gym close to his office.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    You might want to visit www.PacktPub.com for support files and downloads related to your book.

    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 for more details.

    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.

    http://PacktLib.PacktPub.com

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across 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 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 nine entirely free books. Simply use your login credentials for immediate access.

    Preface

    If you've been a software developer for a long time, you have certainly participated in software conferences or developer forums and experienced many interesting conversations. They start out well with one of the developers describing a cool development process that he/she follows, and then another developer strikes with a cutting-edge technology or tool or a mind-boggling enterprise integration pattern that he/she works with. Each speaker attempts to outdo the last speaker. Old timers speak about ancient machines that had to be programmed with punch cards or switches, where they had only few bytes of RAM, or they start describing COBOL as a dynamic language that follows the Model View Presenter pattern. Ask them three questions: How do you unit test your program?, Can you alleviate high blood pressure by monitoring your pressure more often?, and Have you ever maintained your own code?

    I asked the first question to more than 200 developers. Believe me, 80 percent of developers replied, We pay our testers or we have skilled testers. Five percent said, Our customers test the software. Now the remaining 15 percent do unit testing and use print statements or write JUnit tests.

    It is insane to keep doing things the same way and expect them to improve. Any program is only as good as it is useful; so, before applying complex tools, patterns, or APIs, we should verify whether our software functions or not. We should configure our development environment to provide us quick feedback of what is being developed. Automated JUnit tests help us verify our assumptions continuously. Side effects are detected quickly and this saves time.

    As Martin Fowler states Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

    We can write obfuscated code to impress our peers, but writing readable code is an art. Readability is a code quality.

    Can you treat high blood pressure by monitoring your blood pressure more often? No, you need medication. Similarly, we should analyze our code to improve our code quality. Static code analysis tools suggest corrective actions, which means we should continuously monitor our code quality.

    Always code as though the guy who ends up maintaining your code will be a violent psychopath who knows where you live. We work in brand new greenfield projects and also in existing brownfield projects. Greenfield projects always follow test-driven development to deliver maintainable and testable code.

    Test-driven development is an evolutionary development approach. It offers test-first development where the production code is written only to satisfy a test. The simple idea of writing a test first reduces the extra effort of writing unit tests after coding. In test-driven development, test doubles and mock objects are extensively used to mock out external dependencies. Mockito is an open source mock unit testing framework for Java. It allows mock object creation, verification, and stubbing.

    As Winston Churchill states We make a living by what we get, but we make a life by what we give.

    We inherit the legacy code from someone else—it may come from a very old existing project, from other teams who cannot maintain the code, or may be acquired from another company. However, it is our duty to improve the quality.

    This book is an advanced-level guide that will help software developers to get complete expertise in unit testing in the JUnit framework using Mockito as the mocking framework. The focus of the book is to provide readers with comprehensive details on how effectively JUnit tests can be written. Build scripts can be customized to automate unit tests, code quality can be monitored using static code analysis tools and code quality dashboards, and tests can be written for the Web and database components. Legacy code can be refactored. Test-driven development and Mockito can be used for software development; JUnit best practices can be followed.

    Armed with the knowledge of advanced JUnit concepts, test automation, build scripting tools, the mocking framework, code coverage tools, static code analysis tools, web tier unit testing, database tier unit testing, test-driven development, and refactoring legacy code, you will be pleasantly surprised as how quickly and easily you can write high-quality clean, readable, testable, maintainable, and extensible code. With these kinds of skills in your next software conference, you can impress the participants.

    What this book covers

    Chapter 1, JUnit 4 – a Total Recall, covers the unit testing concept, the JUnit 4 framework, the Eclipse setup, and advance features of JUnit 4. It covers the JUnit 4 framework briefly to get you up and running. We will discuss the concept surrounding JUnit essentials, annotations, assertion, the @RunWith annotation, and exception handling so that you have an adequate background on how JUnit 4 works. Advanced readers can skip to the next section. JUnit 4++ explores the advanced topics of JUnit 4 and deep dives into the following topics: parameterized test, matchers and assertThat, assumption, theory, timeout, categories, rules, test suites, and test order.

    Chapter 2, Automating JUnit Tests, focuses on getting the reader quickly started with the Extreme Programming (XP) concept, Continuous Integration (CI), benefits of CI, and JUnit test automation using various tools such as Gradle, Maven, Ant, and Jenkins. By the end of this chapter, the reader will be able to write build scripts using Gradle, Maven, and Ant and configure Jenkins to execute the build scripts.

    Chapter 3, Test Doubles, illustrates the concept of test doubles and explains various test double types, such as mock, fake, dummy, stub, and spy.

    Chapter 4, Progressive Mockito, distills the Mockito framework to its main core and provides technical examples. No previous knowledge of mocking is necessary. By the end of this chapter, the reader will be able to use advanced features of the Mockito framework; start behavior-driven development using Mockito; and write readable, maintainable, and clean JUnit tests using Mockito.

    Chapter 5, Exploring Code Coverage, unfolds the code coverage concept, code coverage tools, and provides step-by-step guidance to generate coverage reports using various build scripts. The following topics are covered: code coverage; branch and line coverage; coverage tools—Clover, Cobertura, EclEmma, and JaCoCo; measuring coverage using Eclipse plugins; and using Ant, Maven, and Gradle to generate reports. By the end of this chapter, the reader will be able to configure Eclipse plugins and build scripts to measure code coverage.

    Chapter 6, Revealing Code Quality, explores the static code analysis and code quality improvement. By the end of this chapter, the reader will be able to configure the SONAR dashboard, set up Eclipse plugins, configure Sonar runner, and build scripts to analyze code quality using PMD, FindBugs, and Checkstyle.

    Chapter 7, Unit Testing the Web Tier, deals with unit testing the web tier or presentation layer. It covers unit testing servlets, playing with Spring MVC, and working with the Model View Presenter pattern. By the end of this chapter, the reader will be able to unit test the web tier components and isolate the view components from the presentation logic.

    Chapter 8, Playing with Data, covers the unit testing of the database layer. Topics such as separating concerns, unit testing the persistence logic, simplifying persistence with Spring, verifying the system integrity, and writing integration tests with Spring are explained. By the end of this chapter, the reader will be able to unit test the data access layer components in isolation from the database, write neat JDBC code using Spring, and write integration tests using the Spring API.

    Chapter 9, Solving Test Puzzles, explains the importance of unit testing in greenfield and brownfield projects. Topics such as working with testing impediments, identifying constructor issues, realizing initialization issues, working with private methods, working with final methods, exploring static method issues, working with final classes, learning new concerns, exploring static variables and blocks, and test-driven development are covered. By the end of this chapter, the reader will be able to write unit tests for the legacy code; refactor the legacy code to improve the design of existing code; start writing simple, clean, and maintainable code following test-first and test-driven developments; and refactor code to improve code quality.

    Chapter 10, Best Practices, focuses on JUnit guidelines and best practices for writing clean, readable, and maintainable JUnit test cases. It covers working with assertions, handling exceptions, and working with test smells. By the end of this chapter, the reader will be able to write clean and maintainable test cases.

    What you need for this book

    You will need the following software to be installed before you run the examples:

    Java 6 or higher: JDK 1.6 or higher can be downloaded from the following Oracle website:

    http://www.oracle.com/technetwork/java/javase/downloads/index.html

    Eclipse editor: The latest version of Eclipse is Kepler (4.3). Kepler can be downloaded from the following website:

    http://www.eclipse.org/downloads/

    Mockito is required for creation, verification of mock objects, and stubbing. It can be downloaded from the following website:

    https://code.google.com/p/mockito/downloads/list

    Who this book is for

    This book is for advanced to novice level software testers or developers who use Mockito in the JUnit framework. Reasonable knowledge and understanding of unit testing elements and applications is required.

    This book is ideal for developers who have some experience in Java application development as well as some basic knowledge of JUnit testing, but it covers the basic fundamentals of JUnit testing, test automation, static code analysis, legacy code refactoring, and test-driven development to get you acquainted with these concepts before using them.

    Enjoying the preview?
    Page 1 of 1