Book Image

Mastering Unit Testing Using Mockito and JUnit

By : Sujoy Acharya
Book Image

Mastering Unit Testing Using Mockito and JUnit

By: Sujoy Acharya

Overview of this book

Table of Contents (17 chapters)
Mastering Unit Testing Using Mockito and JUnit
About the Author
About the Reviewers


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:

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.


In this book, you will find a number of styles of text 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: "The afterClass and beforeClass methods are executed only once."

A block of code is set as follows:

  public void currencyRoundsOff() throws Exception {
    assertEquals("$101.00", CurrencyFormatter.format(100.999));

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

public class LocaleTest {
  private Locale defaultLocale;
  public void setUp() {
    defaultLocale = Locale.getDefault();
  public void restore() {
  public void currencyRoundsOff() throws Exception {

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

green(com.packtpub.junit.recap.rule.TestWatcherTest) success!

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Click on Java build path on the left-hand side and open the Libraries tab."


Warnings or important notes appear in a box like this.


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 may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via 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 on

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 for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.


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 would 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, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from


Piracy of copyright 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.


You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it.