Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
MOCKITO COOKBOOK
MOCKITO COOKBOOK

MOCKITO COOKBOOK: Over 65 recipes to get you up and running with unit testing using Mockito.

eBook
€25.99 €28.99
Paperback
€35.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

MOCKITO COOKBOOK

Chapter 2. Creating Mocks

In this chapter, we will cover the following recipes:

  • Creating mocks in code
  • Creating mocks with annotations
  • Creating mocks with a different default answer
  • Creating mocks with different default answers with annotations
  • Creating mocks with custom configuration
  • Creating mocks of final classes with PowerMock
  • Creating mocks of enums with PowerMock

Introduction

Mockito, as the name suggests, is all about working with mocks. It is worth mentioning that before you go and start mocking every class that is in your codebase, it's good to really understand the idea behind mocking and when to mock an object.

While performing unit testing, you will want to test your system in isolation. You're doing it because you want to test a part of the system as a unit and control any external interactions. Remember that in new, well-designed code, your system should follow the SOLID principles (for more details, check out Uncle Bob's blog at http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod and read Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin, which is available at http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445). The complete description about what SOLID stands for is given as follows:

  • (S) Single responsibility principle: A class should have only a single...

Creating mocks in code

Before a mock is interacted with, it needs to be created. Mockito gives you several overloaded versions of the Mockito.mock method. Let's take a look at a few of them:

  • mock(Class<T> classToMock): This method creates a mock of a given class with a default answer set to returning default values (if not overriden by a custom Mockito configuration). When creating mocks in code, you will most likely be using this method.
  • mock(Class<T> classToMock, String name): This method creates a mock of a given class with a default answer set to returning default values. It also sets a name to the mock. This name is present in all verification messages. That's very useful in debugging, since it allows you to distinguish the mocks.
  • mock(Class<T> classToMock, Answer defaultAnswer): This method creates a mock of a given class with a default answer set to the one passed as the method's argument. In other words, all of the nonstubbed mock's method will...

Creating mocks with annotations

In the previous recipe, we saw how to create a mock by means of the Mockito.mock static method. It's much better, however, to use Mockito's annotations to make your tests look even nicer. Before going into the details of how to do it, let's take a closer look at the system under test (it's the same as in the previous recipe, but in order for you not to jump around pages, let's take a look at it here).

Getting ready

In this recipe, our system under test is a class that calculates a mean value of tax factors retrieved through a web service, as shown in the following code:

public class MeanTaxFactorCalculator {

    private final TaxService taxService;

    public MeanTaxFactorCalculator(TaxService taxService) {
        this.taxService = taxService;
    }

    public double calculateMeanTaxFactorFor(Person person) {
        double currentTaxFactor = taxService.getCurrentTaxFactorFor(person);
        double anotherTaxFactor = taxService...

Creating mocks with a different default answer

If not changed by the custom configuration, Mockito sets the mock ReturnsEmptyValues answer by default (for details on that answer, please check the subsequent There's more... section). Note that in Chapter 4, Stubbing Behavior of Mocks, where we deal with stubbing of particular methods, you can learn how to stub particular methods with a custom answer.

In the following recipe, we will see how to change the default answer to a custom or a predefined one.

Getting ready

It is more than probable that you will not ever need to create a custom answer for Mockito—there are plenty of them already bundled in Mockito and there is no need to reinvent the wheel. Why would you want to create a custom answer anyway? Let's take a look at a couple of possible answers to that question:

  • It is possible that for debugging purposes, you would like to log the arguments that were passed to the stubbed method
  • You could also want to perform some more complex...

Creating mocks with different default answers with annotations

In the previous recipe, you have seen how to pass an implementation of the Answer interface to your mock to change its default behavior. In this recipe, we will focus on doing the same when creating mocks using annotations.

All versions of Mockito up until version 1.9.5 allow you to pass only elements of the Answers enum that delegate to answers present in the public Mockito API, as the arguments of the annotation. In the next Mockito release, there should be a possibility of passing a custom answer too, but until then it's not possible to do that.

Getting ready

In the following code, our system is a class that, based on the person's country, collects his Internal Revenue Service (IRS) address and formats it properly:

public class TaxFactorInformationProvider {

    private final TaxService taxService;

    public TaxFactorInformationProvider(TaxService taxService) {
        this.taxService = taxService;
    }

    public...

Introduction


Mockito, as the name suggests, is all about working with mocks. It is worth mentioning that before you go and start mocking every class that is in your codebase, it's good to really understand the idea behind mocking and when to mock an object.

While performing unit testing, you will want to test your system in isolation. You're doing it because you want to test a part of the system as a unit and control any external interactions. Remember that in new, well-designed code, your system should follow the SOLID principles (for more details, check out Uncle Bob's blog at http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod and read Agile Software Development, Principles, Patterns, and Practices, Robert C. Martin, which is available at http://www.amazon.com/Software-Development-Principles-Patterns-Practices/dp/0135974445). The complete description about what SOLID stands for is given as follows:

  • (S) Single responsibility principle: A class should have only a single responsibility...

Creating mocks in code


Before a mock is interacted with, it needs to be created. Mockito gives you several overloaded versions of the Mockito.mock method. Let's take a look at a few of them:

  • mock(Class<T> classToMock): This method creates a mock of a given class with a default answer set to returning default values (if not overriden by a custom Mockito configuration). When creating mocks in code, you will most likely be using this method.

  • mock(Class<T> classToMock, String name): This method creates a mock of a given class with a default answer set to returning default values. It also sets a name to the mock. This name is present in all verification messages. That's very useful in debugging, since it allows you to distinguish the mocks.

  • mock(Class<T> classToMock, Answer defaultAnswer): This method creates a mock of a given class with a default answer set to the one passed as the method's argument. In other words, all of the nonstubbed mock's method will act as defined in...

Creating mocks with annotations


In the previous recipe, we saw how to create a mock by means of the Mockito.mock static method. It's much better, however, to use Mockito's annotations to make your tests look even nicer. Before going into the details of how to do it, let's take a closer look at the system under test (it's the same as in the previous recipe, but in order for you not to jump around pages, let's take a look at it here).

Getting ready

In this recipe, our system under test is a class that calculates a mean value of tax factors retrieved through a web service, as shown in the following code:

public class MeanTaxFactorCalculator {

    private final TaxService taxService;

    public MeanTaxFactorCalculator(TaxService taxService) {
        this.taxService = taxService;
    }

    public double calculateMeanTaxFactorFor(Person person) {
        double currentTaxFactor = taxService.getCurrentTaxFactorFor(person);
        double anotherTaxFactor = taxService.getCurrentTaxFactorFor(person...
Left arrow icon Right arrow icon

Description

This is a focused guide with lots of practical recipes with presentations of business issues and presentation of the whole test of the system. This book shows the use of Mockito's popular unit testing frameworks such as JUnit, PowerMock, TestNG, and so on. If you are a software developer with no testing experience (especially with Mockito) and you want to start using Mockito in the most efficient way then this book is for you. This book assumes that you have a good knowledge level and understanding of Java-based unit testing frameworks.

What you will learn

  • Create beautiful tests using Mockito
  • Create mocks and spies in a number of ways
  • Implement best practices to perform tests with Mockito
  • Extend Mockito with other popular Javabased unit testing frameworks such as JUnit and PowerMock
  • Stub behavior of mocks and spies
  • Verify test doubles with Mockito
  • Write good tests using Mockito
  • Integrate Mockito with DI systems
  • Compare Mockito to other mocking frameworks
  • Verify the behavior of your system under test

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 24, 2014
Length: 284 pages
Edition : 1st
Language : English
ISBN-13 : 9781783982745
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Jun 24, 2014
Length: 284 pages
Edition : 1st
Language : English
ISBN-13 : 9781783982745
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 96.97
MOCKITO COOKBOOK
€35.99
Mockito Essentials
€24.99
MASTERING UNIT TESTING USING MOCKITO AND JUNIT
€35.99
Total 96.97 Stars icon

Table of Contents

11 Chapters
1. Getting Started with Mockito Chevron down icon Chevron up icon
2. Creating Mocks Chevron down icon Chevron up icon
3. Creating Spies and Partial Mocks Chevron down icon Chevron up icon
4. Stubbing Behavior of Mocks Chevron down icon Chevron up icon
5. Stubbing Behavior of Spies Chevron down icon Chevron up icon
6. Verifying Test Doubles Chevron down icon Chevron up icon
7. Verifying Behavior with Object Matchers Chevron down icon Chevron up icon
8. Refactoring with Mockito Chevron down icon Chevron up icon
9. Integration Testing with Mockito and DI Frameworks Chevron down icon Chevron up icon
10. Mocking Libraries Comparison Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(4 Ratings)
5 star 25%
4 star 75%
3 star 0%
2 star 0%
1 star 0%
Gualtiero Testa Aug 04, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good. This is a well written and very interesting reading for everybody involved in Java testing.This book is not intended to be a primer on testing in general and on Mockito in particular. Beginners should look for an introduction on automated testing before start with Mockito Cookbook.The author covers everything related to the Mockito library and also on several additional libraries and tools connected to Mockito, like, for example, PowerMock.The book starts with an introductive chapter on Mockito installation and basic usage with both JUnit and TestNG.The core of the book is the chapters from 2 to 7 where the author explain, as recipes, several techniques to test easy and difficult to test code.Final book chapters are on legacy code testing, testing using frameworks like Spring and Mockito compared to other mocking libraries.In all examples, sometimes a bit repetitive due to the recipes approach, the author also explain general testing and object oriented programming approaches and methodologies. This is of course limited in space but there are plenty of references.
Amazon Verified review Amazon
Peter Major Sep 14, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This book introduces the reader to the world of mocks and spies, and explains stubbing in great detail. Whilst this is a cookbook, it also contains quite useful guidelines on development paradigms and describes how Mockito implements the different mocking/stubbing mechanisms.I believe the recipes cover essentially all the viable use-cases for stubbing methods - even if those sometimes require additional libraries such as PowerMock. When going through the recipes, they may seem a bit repetitive, however the examples are always quite similar, making it very easy to find what is needed. Each recipe has a "How it Works" and most has a "There's more" section to allow the reader to acquire more information on the current subject. There can be found quite a few external references in the book, should the reader want to go into even more details.The examples are mainly written using JUnit, but TestNG is also covered.Personally I would recommend buying this book, it is certainly a good source of knowledge about mocking.
Amazon Verified review Amazon
Alexandros Koufoudakis Aug 22, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
“Mockito Cookbook” is a useful book, by means of which, you can discover Mockito testing framework and start using it in the matter of days.It starts with the short introduction of the test doubles, set up of Mockito for JUnit and TestNG, and a very basic example of using it. The first chapter of the book also gives concise recommendations on using Mockito.Further the book focuses on the creation of different types of test doubles (stubs, mocks, spies) and their behavior. Each chapter gives examples, using standard Mockito API and BDD Mockito API. The section ends with the description of verification of test doubles and their behavior.Final chapters are dedicated to the integration testing with Mockito and Spring framework and comparison of mocking libraries: Mockito, JMockit, JMock, and Spock.In general, I have a very positive impression after reading the book. I was a complete newbie in Mockito before starting reading it. Of course, it didn’t make me an expert in a week; however, I started understanding BDD code and Mockito API much better. It is much easier for me now to understand test cases, which are written by my colleagues.Unfortunately, I have to note that the author repeats certain phrases from chapter to chapter. That space could have been used for a bit deeper explanation of best practices or theoretical aspects (even if it is a cookbook).Nevertheless, if you are a newbie in BDD, TDD, and Mockito and you want to become quickly up to speed with the framework, this book is the right choice.
Amazon Verified review Amazon
Shubham Aggarwal May 22, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
This is a nice book but it tries to cover Breadth instead of Depth.I bought this book in an assumption that different testing scenarios would be covered but this wasn't the case. While the book is good in covering a large number of testing framework integration but it doesn't cover the depth of test cases. Also, I though the explanations were not quite well as they assumed too much knowledge from the point of the reader.Still a good read.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.