Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
MOCKITO COOKBOOK
MOCKITO COOKBOOK

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

eBook
$19.99 $28.99
Paperback
$47.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

MOCKITO COOKBOOK

Chapter 1. Getting Started with Mockito

In this chapter, we will cover the following recipes:

  • Adding Mockito to a project's classpath
  • Getting started with Mockito for JUnit
  • Getting started with Mockito for TestNG
  • Mockito best practices - test behavior, not implementation
  • Adding Mockito hints to exception messages in JUnit (Experimental)
  • Adding additional Mockito warnings to your tests in JUnit (Experimental)

Introduction

For those who don't know Mockito at all, I'd like to write a really short introduction about it.

Mockito is an open source framework for Java that allows you to easily create test doubles (mocks). What makes Mockito so special is that it eliminates the common expect-run-verify pattern (which was present, for example, in EasyMock—please refer to http://monkeyisland.pl/2008/02/24/can-i-test-what-i-want-please for more details) that in effect leads to a lower coupling of the test code to the production code as such. In other words, one does not have to define the expectations of how the mock should behave in order to verify its behavior. That way, the code is clearer and more readable for the user.

On one hand, Mockito has a very active group of contributors and is actively maintained; on the other hand, unfortunately, by the time this book is written, the last Mockito release (Version 1.9.5) have been in October 2012.

You may ask yourself the question, "Why should I even bother to use Mockito in the first place?" Out of many choices, Mockito offers the following key features:

  • There is no expectation phase for Mockito—you can either stub or verify the mock's behavior
  • You are able to mock both interfaces and classes
  • You can produce little boilerplate code while working with Mockito by means of annotations
  • You can easily verify or stub with intuitive argument matchers

Before diving into Mockito as such, one has to understand the concept behind System Under Test (SUT) and test doubles. We will base our work on what Gerard Meszaros has defined in the xUnit Patterns (http://xunitpatterns.com/Mocks,%20Fakes,%20Stubs%20and%20Dummies.html).

SUT (http://xunitpatterns.com/SUT.html) describes the system that we are testing. It doesn't have to necessarily signify a class or any part of the application that we are testing or even the whole application as such.

As for test doubles (http://www.martinfowler.com/bliki/TestDouble.html), it's an object that is used only for testing purposes, instead of a real object. Let's take a look at different types of test doubles:

  • Dummy: This is an object that is used only for the code to compile—it doesn't have any business logic (for example, an object passed as a parameter to a method)
  • Fake: This is an object that has an implementation but it's not production ready (for example, using an in-memory database instead of communicating with a standalone one)
  • Stub: This is an object that has predefined answers to method executions made during the test
  • Mock: This is an object that has predefined answers to method executions made during the test and has recorded expectations of these executions
  • Spy: These are objects that are similar to stubs, but they additionally record how they were executed (for example, a service that holds a record of the number of sent messages)

An additional remark is also related to testing the output of our application. Throughout the book, you will see that the tests (in general, all of them apart from the chapter related to verification) are based on the assertion of behavior instead of the checking of implementation. The more decoupled your test code is from your production code, the better, since you will have to spend less time (or even none) on modifying your tests after you change the implementation of the code.

Coming back to the chapter's content—this chapter is all about getting started with Mockito. We will begin with how to add Mockito to your classpath. Then, we'll see a simple setup of tests for both JUnit and TestNG test frameworks. Next, we will check why it is crucial to assert the behavior of the system under test instead of verifying its implementation details. Finally, we will check out some of Mockito's experimental features, adding hints and warnings to the exception messages. The very idea of the following recipes is to prepare your test classes to work with Mockito and to show you how to do this with as little boilerplate code as possible.

Due to my fondness for the behavior driven development (http://dannorth.net/introducing-bdd/ first introduced by Dan North), I'm using Mockito's BDDMockito and AssertJ's BDDAssertions static methods to make the code even more readable and intuitive in all the test cases. Also, please read Szczepan Faber's blog (author of Mockito) about the given, when, then separation in your test methods—http://monkeyisland.pl/2009/12/07/given-when-then-forever/—since these are omnipresent throughout the book.

Even though some of the previous methods might sound not too clear to you or the test code looks complicated—don't worry, it will all be explained throughout the book. I don't want the book to become a duplication of the Mockito documentation, which is of high quality—I would like you to take a look at good tests and get acquainted with Mockito syntax from the beginning. What's more, I've used static imports in the code to make it even more readable, so if you get confused with any of the pieces of code, it would be best to consult the repository and the code as such.

Adding Mockito to a project's classpath

Adding Mockito to a project's classpath is as simple as adding one of the two jars to your project's classpath:

  • mockito-all: This is a single jar with all dependencies (with the hamcrest and objenesis libraries—as of June 2011).
  • mockito-core: This is only Mockito core (without hamcrest or objenesis). Use this if you want to control which version of hamcrest or objenesis is used.

How to do it...

If you are using a dependency manager that connects to the Maven Central Repository, then you can get your dependencies as follows (examples of how to add mockito-all to your classpath for Maven and Gradle):

For Maven, use the following code:

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

For Gradle, use the following code:

testCompile "org.mockito:mockito-all:1.9.5"

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. 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.

If you are not using any of the dependency managers, you have to either download mockito-all.jar or mockito-core.jar and add it to your classpath manually (you can download the jars from https://code.google.com/p/mockito/downloads/list). To see more examples of adding Mockito to your classpath, please check the book, Instant Mockito, Marcin Grzejszczak, Packt Publishing, for more examples of adding Mockito to your classpath (it includes Ant, Buildr, Sbt, Ivy, Gradle, and Maven).

See also

Getting started with Mockito for JUnit

Before going into details regarding Mockito and JUnit integration, it is worth mentioning a few words about JUnit.

JUnit is a testing framework (an implementation of the xUnit framework) that allows you to create repeatable tests in a very readable manner. In fact, JUnit is a port of Smalltalk's SUnit (both the frameworks were originally implemented by Kent Beck). What is important in terms of JUnit and Mockito integration is that under the hood, JUnit uses a test runner to run its tests (from xUnit—test runner is a program that executes the test logic and reports the test results).

Mockito has its own test runner implementation that allows you to reduce boilerplate in order to create test doubles (mocks and spies) and to inject them (either via constructors, setters, or reflection) into the defined object. What's more, you can easily create argument captors. All of this is feasible by means of proper annotations as follows:

  • @Mock: This is used for mock creation
  • @Spy: This is used to create a spy instance
  • @InjectMocks: This is used to instantiate the @InjectMock annotated field and inject all the @Mock or @Spy annotated fields into it (if applicable)
  • @Captor: This is used to create an argument captor

By default, you should profit from Mockito's annotations to make your code look neat and to reduce the boilerplate code in your application.

Getting ready

In order to add JUnit to your classpath, if you are using a dependency manager that connects to the Maven Central Repository, then you can get your dependencies as follows (examples for Maven and Gradle):

To add JUnit in Maven, use the following code:

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

To add JUnit in Gradle, use the following code:

testCompile('junit:junit:4.11')

If you are not using any of the dependency managers, you have to download the following jars:

  • junit.jar
  • hamcrest-core.jar

Add the downloaded files to your classpath manually (you can download the jars from https://github.com/junit-team/junit/wiki/Download-and-Install).

For this recipe, our system under test will be a MeanTaxFactorCalculator class that will call an external service, TaxService, to get the current tax factor for the current user. It's a tax factor and not tax as such, since for simplicity, we will not be using BigDecimals but doubles, and I'd never suggest using doubles to anything related to money, as follows:

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);
        return (currentTaxFactor + anotherTaxFactor) / 2;
    }

}

How to do it...

To use Mockito's annotations, you have to perform the following steps:

  1. Annotate your test with the @RunWith(MockitoJUnitRunner.class).
  2. Annotate the test fields with the @Mock or @Spy annotation to have either a mock or spy object instantiated.
  3. Annotate the test fields with the @InjectMocks annotation to first instantiate the @InjectMock annotated field and then inject all the @Mock or @Spy annotated fields into it (if applicable).
  4. Annotate the test fields with the @Captor annotation to make Mockito instantiate an argument captor (refer to Chapter 6, Verifying Test Doubles, for more details).

The following snippet shows the JUnit and Mockito integration in a test class that verifies the SUT's behavior (remember that I'm using BDDMockito.given(...) and AssertJ's BDDAssertions.then(...) static methods; refer to Chapter 7, Verifying Behavior with Object Matchers, for how to work with AssertJ or how to do the same with Hamcrest's assertThat(...) method):

@RunWith(MockitoJUnitRunner.class)
public class MeanTaxFactorCalculatorTest {

    static final double TAX_FACTOR = 10;

    @Mock TaxService taxService;

    @InjectMocks MeanTaxFactorCalculator systemUnderTest;

    @Test
    public void should_calculate_mean_tax_factor() {
        // given
        given(taxService.getCurrentTaxFactorFor(any(Person.class))).willReturn(TAX_FACTOR);

        // when
        double meanTaxFactor = systemUnderTest.calculateMeanTaxFactorFor(new Person());

        // then
        then(meanTaxFactor).isEqualTo(TAX_FACTOR);
    }

}

Note

To profit from Mockito's annotations using JUnit, you just have to annotate your test class with @RunWith(MockitoJUnitRunner.class).

How it works...

The Mockito test runner will adapt its strategy depending on the version of JUnit. If there exists a org.junit.runners.BlockJUnit4ClassRunner class, it means that the codebase is using at least JUnit in Version 4.5.What eventually happens is that the MockitoAnnotations.initMocks(...) method is executed for the given test, which initializes all the Mockito annotations (for more information, check the subsequent There's more… section).

There's more...

You may have a situation where your test class has already been annotated with a @RunWith annotation and, seemingly, you may not profit from Mockito's annotations. In order to achieve this, you have to call the MockitoAnnotations.initMocks method manually in the @Before annotated method of your test, as shown in the following code:

public class MeanTaxFactorCalculatorTest {

    static final double TAX_FACTOR = 10;

    @Mock TaxService taxService;

    @InjectMocks MeanTaxFactorCalculator systemUnderTest;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void should_calculate_mean_tax_factor() {
        // given
        given(taxService.getCurrentTaxFactorFor(Mockito.any(Person.class))).willReturn(TAX_FACTOR);

        // when
        double meanTaxFactor = systemUnderTest.calculateMeanTaxFactorFor(new Person());

        // then
        then(meanTaxFactor).isEqualTo(TAX_FACTOR);
    }

}

Note

To use Mockito's annotations without a JUnit test runner, you have to call the MockitoAnnotations.initMocks method and pass the test class as its parameter.

Mockito checks whether the user has overridden the global configuration of AnnotationEngine and, if this is not the case, the InjectingAnnotationEngine implementation is used to process annotations in tests. What is done internally is that the test class fields are scanned for annotations and proper test doubles are initialized and injected into the @InjectMocks annotated object (either by a constructor, property setter, or field injection, in that precise order).

Note

You have to remember several factors related to the automatic injection of test doubles as follows:

  • If Mockito is not able to inject test doubles into the @InjectMocks annotated fields through either of the strategies, it won't report failure—the test will continue as if nothing happened (and most likely, you will get NullPointerException).
  • For constructor injection, if arguments cannot be found, then null is passed
  • For constructor injection, if nonmockable types are required in the constructor, then the constructor injection won't take place.
  • For other injection strategies, if you have properties with the same type (or same erasure) and if Mockito matches mock names with a field/property name, it will inject that mock properly. Otherwise, the injection won't take place.
  • For other injection strategies, if the @InjectMocks annotated object wasn't previously initialized, then Mockito will instantiate the aforementioned object using a no-arg constructor if applicable.

See also

Getting started with Mockito for TestNG

Before going into details regarding Mockito and TestNG integration, it is worth mentioning a few words about TestNG.

TestNG is a unit testing framework for Java that was created, as the author defines it on the tool's website (refer to the See also section for the link), out of frustration for some JUnit deficiencies. TestNG was inspired by both JUnit and TestNG and aims at covering the whole scope of testing—from unit, through functional, integration, end-to-end tests, and so on. However, the JUnit library was initially created for unit testing only.

The main differences between JUnit and TestNG are as follows:

  • The TestNG author disliked JUnit's approach of having to define some methods as static to be executed before the test class logic gets executed (for example, the @BeforeClass annotated methods)—that's why in TestNG you don't have to define these methods as static
  • TestNG has more annotations related to method execution before single tests, suites, and test groups
  • TestNG annotations are more descriptive in terms of what they do, for example, the JUnit's @Before versus TestNG's @BeforeMethod

Mockito in Version 1.9.5 doesn't provide any out-of-the-box solution to integrate with TestNG in a simple way, but there is a special Mockito subproject for TestNG (refer to the See also section for the URL) that should be part one of the subsequent Mockito releases. In the following recipe, we will take a look at how to profit from that code and that very elegant solution.

Getting ready

When you take a look at Mockito's TestNG subproject on the Mockito GitHub repository, you will find that there are three classes in the org.mockito.testng package, as follows:

  • MockitoAfterTestNGMethod
  • MockitoBeforeTestNGMethod
  • MockitoTestNGListener

Unfortunately, until this project eventually gets released, you have to just copy and paste those classes to your codebase.

How to do it...

To integrate TestNG and Mockito, perform the following steps:

  1. Copy the MockitoAfterTestNGMethod, MockitoBeforeTestNGMethod, and MockitoTestNGListener classes to your codebase from Mockito's TestNG subproject.
  2. Annotate your test class with @Listeners(MockitoTestNGListener.class).
  3. Annotate the test fields with the @Mock or @Spy annotation to have either a mock or spy object instantiated.
  4. Annotate the test fields with the @InjectMocks annotation to first instantiate the @InjectMock annotated field and inject all the @Mock or @Spy annotated fields into it (if applicable).
  5. Annotate the test fields with the @Captor annotation to make Mockito instantiate an argument captor (check Chapter 6, Verifying Test Doubles, for more details).

Now let's take a look at this snippet that, using TestNG, checks whether the mean tax factor value has been calculated properly (remember that I'm using the BDDMockito.given(...) and AssertJ's BDDAssertions.then(...) static methods—refer to Chapter 7, Verifying Behavior with Object Matchers, on how to work with Hamcrest assertThat(...) method):

@Listeners(MockitoTestNGListener.class)
public class MeanTaxFactorCalculatorTestNgTest {

    static final double TAX_FACTOR = 10;

    @Mock TaxService taxService;

    @InjectMocks MeanTaxFactorCalculator systemUnderTest;

    @Test
    public void should_calculate_mean_tax_factor() {
        // given
        given(taxService.getCurrentTaxFactorFor(any(Person.class))).willReturn(TAX_FACTOR);

        // when
        double meanTaxFactor = systemUnderTest.calculateMeanTaxFactorFor(new Person());

        // then
        then(meanTaxFactor).isEqualTo(TAX_FACTOR);
    }

}

How it works...

TestNG allows you to register custom listeners (your listener class has to implement the IInvokedMethodListener interface). Once you do this, the logic inside the implemented methods will be executed before and after every configuration, and test methods get called. Mockito provides you with a listener whose responsibilities are as follows:

  • Initialize mocks annotated with the @Mock annotation (it is done only once)
  • Validate the usage of Mockito after each test method

Note

Remember that with TestNG all mocks are reset (or initialized if it hasn't already been done) before any TestNG method!

See also

Mockito best practices – test behavior not implementation

Once you start testing with Mockito you might be tempted to start mocking everything that gets in your way. What is more, you may have heard that you have to mock all of the collaborators of the class and then verify whether those test doubles executed the desired methods. Of course, you can code like that, but since it is best to be a pragmatic programmer, you should ask yourself the question whether you would be interested in changing the test code each time someone changes the production code, even though the application does the same things.

It's worth going back to distinguishing stubs from mocks. Remember that, if you create a mock, it's for the sake of the verification of its method execution. If you are only interested in the behavior of your test double—if it behaves as you tell it to—then you have a stub. In the vast majority of cases, you shouldn't be interested in whether your test double has executed a particular method; you should be more interested in whether your application does what it is supposed to do. Also, remember that there are cases where it makes no sense to create a stub of an external dependency—it all depends on how you define the system under test.

It might sound a little confusing but, hopefully, the following recipe will clear things up. We will take a look at the simple example of a tax factor summing class that changes in time (whereas its tests should not change much).

Getting ready

Let's assume that we have the following tax factor calculator that calculates a sum of two tax factors:

public class TaxFactorCalculator {

    public double calculateSum(double taxFactorOne, double taxFactorTwo) {
        return taxFactorOne + taxFactorTwo;
    }

}

After some time, it turned out that we read about a library that allows you to hide the implementation details of summing and you decided to rewrite your calculator to use this library. Now your code looks as follows:

public class TaxFactorCalculator {

    private final Calculator calculator;

    public TaxFactorCalculator(Calculator calculator) {
        this.calculator = calculator;
    }

    public double calculateSum(double taxFactorOne, double taxFactorTwo) {
        return calculator.add(taxFactorOne, taxFactorTwo);
    }

}

How to do it...

Since you want to test whether your system under test works fine, you should focus on the following points:

  • Start by writing a test—not with an implementation. That way, you will constantly ask yourself the question of what you want to do and only then will you think about how to do it.
  • Focus on asserting the result—what you want to verify in most cases is whether your system under test works as it is supposed to. You shouldn't care much how exactly it is done.

Let's take a look at a test of the first version of the class (I'm using the BDDMockito.given(...) and AssertJ's BDDAssertions.then(...) static methods—refer to Chapter 7, Verifying Behavior with Object Matchers, for how to work with AssertJ or how to do the same with Hamcrest's assertThat(...) method):

    @Test
    public void should_calculate_sum_of_factors() {
        // given
        TaxFactorCalculator systemUnderTest =new TaxFactorCalculator();
        double taxFactorOne = 1;
        double taxFactorTwo = 2;
        double expectedSum = 3;
        
        // when
        double sumOfFactors = systemUnderTest.calculateSum(taxFactorOne, taxFactorTwo);

        // then
        then(sumOfFactors).isEqualTo(expectedSum);
    }

As you can see, we are testing a class that should add two numbers and produce a result. We are not interested in how it is done—we want to check that the result is satisfactory. Now, assuming that our implementation changed—having a good test would require only to comply to the new way that our system under test is being initialized and the rest of the code remains untouched. In other words, change TaxFactorCalculator systemUnderTest = new TaxFactorCalculator() to TaxFactorCalculator systemUnderTest = new TaxFactorCalculator(new Calculator()). Moreover, since we are checking behavior and not the implementation, we don't have to refactor the test code at all.

See also

Adding Mockito hints to exception messages (JUnit) (Experimental)

When a JUnit test fails, an exception is thrown and a message is presented. Sometimes, it is enough to find a reason for this mistake and to find the solution. Mockito, however, goes a step further and tries to help the developer by giving him additional hints regarding the state of the stubbed methods.

Note

Remember that this feature is experimental and the API, name, or anything related to it may change in time. What is more, the whole feature may get deleted in time!

Getting ready

For this recipe, let's assume that our system is the MeanTaxFactorCalculator class that calculates tax through TaxService, which has two methods—performAdditionalCalculation() and getCurrentTaxFactorFor(...). For the sake of this example, let's assume that only the latter is used to calculate the mean value:

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);
        return (currentTaxFactor + anotherTaxFactor) / 2;
    }

}

We wanted to check whether our system under test is calculating the proper result, so we wrote the following test but made a mistake and stubbed a wrong method (I'm using the BDDMockito.given(...) and AssertJ's BDDAssertions.then(...) static methods—refer Chapter 7, Verifying Behavior with Object Matchers, for how to work with AssertJ or how to do the same with Hamcrest's assertThat(...) method):

@RunWith(MockitoJUnitRunner.class)
public class MeanTaxFactorCalculatorTest {

    static final double UNUSED_VALUE = 10;

    @Test
    public void should_calculate_mean_tax_factor() {
        // given
        TaxService taxService = given(Mockito.mock(TaxService.class).performAdditionalCalculation()).willReturn(UNUSED_VALUE).getMock();
        MeanTaxFactorCalculator systemUnderTest =new MeanTaxFactorCalculator(taxService);

        // when
        double meanTaxFactor = systemUnderTest.calculateMeanTaxFactorFor(new Person());

        // then
        then(meanTaxFactor).isEqualTo(UNUSED_VALUE);
    }

}

The test fails and what we can see is the standard JUnit comparison failure being thrown (presenting only the most important part of the stack trace) as follows:

org.junit.ComparisonFailure:
Expected :10.0
Actual   :0.0

Now let's take a look at how to use Mockito's experimental features to get more Mockito related information appended to the error message.

How to do it...

If you want to have more information presented in your error message, you have to perform the following steps:

  1. Annotate your JUnit test with @RunWith(VerboseMockitoJUnitRunner.class).
  2. Define your mocks and perform stubbing inside the test method (unfortunately, you can't use annotations or initialize fields outside test methods).

What happens next is that additional exception messages can be seen in the exception that is thrown as follows:

org.mockito.internal.exceptions.ExceptionIncludingMockitoWarnings:contains both: actual test failure *and* Mockito warnings.
This stubbing was never used   -> at ...MeanTaxFactorCalculatorTest.should_calculate_mean_tax_factor(MeanTaxFactorCalculatorTest.java:30)

 *** The actual failure is because of: ***

Expected :10.0
Actual   :0.0

How it works...

When the test is run, VerboseMockitoJUnitRunner appends a listener. When the test is started, this listener finds all the stubs through WarningsCollector, including the unused stubs for given mocks.

As the Mockito developers state it in the code, they are indeed using a very hacky way to append a message to the thrown exception after the test fails. The JUnitFailureHacker class is instantiated and, by means of the Whitebox class, the internal state of a private field of the JUnit's Failure object is modified with additional Mockito messages.

Adding additional Mockito warnings to your tests (JUnit) (Experimental)

If you would like Mockito to append some additional warning messages to the console, which would help you when your test fails, then this recipe is perfect for you. It's very much related to the previous one so, in order to understand the background, please refer to the introductory part of the previous recipe.

Note

Remember that this feature is experimental and the API, name, or anything related to it may change in time. What's more, the whole feature may get deleted in time!

How to do it...

If you want to have more information presented in your error message, you have to perform the following steps:

  1. Annotate your JUnit test with @RunWith(ConsoleSpammingMockitoJUnitRunner.class).
  2. Define your mocks and perform stubbing inside the test method (unfortunately, you can't use annotations or initialize fields outside test methods).

What happens then is that additional exception messages gets printed on the console after the exception that is thrown:

This stubbing was never used   -> at ....MeanTaxFactorCalculatorTest.should_calculate_mean_tax_factor(MeanTaxFactorCalculatorTest.java:25)

How it works...

When the test is run, ConsoleSpammingMockitoJUnitRunner appends a listener that finds all the stubs through WarningsCollector, including the unused stubs for given mocks. When all of the warnings get collected, the ConsoleMockitoLogger class prints them to the console after the test has failed.

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
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Indonesia

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

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 $ 128.97
Mockito Essentials
$32.99
MASTERING UNIT TESTING USING MOCKITO AND JUNIT
$47.99
MOCKITO COOKBOOK
$47.99
Total $ 128.97 Stars icon
Banner background image

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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela