DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

  1. DZone
  2. Refcards
  3. Mockito
refcard cover
Refcard #155

Mockito

A Simple, Intuitive Mocking Framework

Covers the testing framework for Java that automatoes unit tests using Test-Driven Deployment or Behavior-Driven Deployment.

Download Refcard
Free PDF for Easy Reference
refcard cover

Written By

author avatar Marcin Zajączkowski
Software Craftsman & Solution Architect, Solid Soft
Table of Contents
► Introduction to Unit Testing ► Configuring Mockito in a Project ► Creating Mock ► Stubbing Method's Returned Value ► Argument Matching ► Stubbing Multiple Calls to the Same Method ► Stubbing Void Methods ► Stubbing with a Custom Answer ► Verifying Behavior ► Verifying Call Order ► Verifying with Argument Matching ► Verifying with Timeout ► Spying on Real Objects ► Annotations ► Changing the Mock Default Return Value ► Resetting Mock ► Limitations ► Further Reading
Section 1

Introduction to Unit Testing

By Marcin Zajaczkowski

A unit test is a test related to a single responsibility of a single class, often referred to as the System Under Test (SUT). The purpose of unit tests is to verify that the code in an SUT works. A tested object usually talks to other objects known as collaborators. These collaborators need to be created so the tested object can be assigned to them in the test. To make unit testing simpler and allow control of all aspects of the execution context, it is useful to replace the real cooperating objects with their fake replacements called test doubles. They look like the originals, but do not have any dependencies to other objects. Test doubles can also be easily programmed with specific expectations, such as recording any interactions they've had.

To make it clearer, try to imagine code for a typical en- terprise system. Now here's a service with some logic that needs two classes to fulfill its responsibility. Both classes then require a few other classes. One of these other classes could be a DAO, which needs access to a database, while yet another requires a message queue. It would be quite an effort to create that hierarchy and provide required resources. There could also be problems while running that kind of test, e.g., long startup times or the inability to test multiple developer stations simultaneously. Using Mocks, though, the same test could be much cleaner and faster.

Test doubles can be divided into a few groups1 :

  • Dummy - an empty object passed in an invocation (usually only to satisfy a compiler when a method ar- gument is required)
  • Fake - an object having a functional implementation, but usually in a simplified form, just to satisfy the test (e.g., an in-memory database)
  • Stub - an object with hardcoded behavior suitable for a given test (or a group of tests)
  • Mock - an object with the ability to a) have a programmed expected behavior, and b) verify the interactions occurring in its lifetime (this object is usually created with the help of mocking framework)
  • Spy - a mock created as a proxy to an existing real object; some methods can be stubbed, while the un- stubbed ones are forwarded to the covered object

Mockito is a mocking framework helpful in creating mocks and spies in a simple and intuitive way, while at the same time providing great control of the whole process.

Section 2

Configuring Mockito in a Project

Mockito artifacts are available in the Maven Central Repository (MCR). The easiest way to make MCR available in your project is to put the following configuration in your dependency manager:

Maven:

1
<dependency>
2
    <groupId>org.mockito</groupId>
3
    <artifactId>mockito‚àícore</artifactId>
4
    <version>1.9.0</version>
5
    <scope>test</scope>
6
    </dependency>

Gradle:

1
1
testCompile “org.mockito:mockito−core:1.9.0“

Ivy:

1
1
<dependency org=”org.mockito” name=”mockito-core” rev=”1.9.0” conf=”test->default”/>

It will add JAR with Mockito classes as well as all re- quired dependencies. Change 1.9.0 with the latest released version of Mockito.

This Refcard is based on the latest stable version 1.9.0. Some things are about to change in the further Mockito versions.

Section 3

Creating Mock

A mock can be created with the help of a static method mock():

1
1
Flower flowerMock=Mockito.mock(Flower.class);

But there's another option: use of @Mock annotation:

2
1
@Mock
2
    private Flower flowerMock;

Warning: If you want to use @Mock or any other Mockito annotations, it is required to call MockitoAnnotations.initMocks( testClass ) or use MockitoJUnit4Runner as a JUnit runner (see the annotation section below for more information).

Section 4

Stubbing Method's Returned Value

One of the basic functions of mocking frameworks is an ability to return a given value when a specific method is called. It can be done using Mockito.when() in conjunction with thenReturn () . This process of defining how a given mock method should behave is called stubbing.

Warning: Note that the examples in this Refcardwere created to demonstrate behaviors of Mockito in a specific context. Of course, when writing the test for your codebase, there is no need to ensure that mocks are stubbed correctly.

​x
1
package info.solidsoft.blog.refcard.mockito;
2
​
3
    import org.testng.annotations.Test;
4
​
5
    import static org.mockito.Mockito.mock;
6
    import static org.mockito.Mockito.when;
7
    import static org.testng.Assert.assertEquals;
8
​
9
    public class SimpleStubbingTest {
10
    public static final int TEST_NUMBER_OF_LEAFS = 5;
11
​
12
    @Test
13
    public void shouldReturnGivenValue() {
14
    Flower flowerMock = mock(Flower.class);
15
    when(flowerMock.getNumberOfLeafs()).thenReturn(TEST_NUMBER_OF_LEAFS);
16
​
17
    int numberOfLeafs = flowerMock.getNumberOfLeafs();
18
​
19
    assertEquals(numberOfLeafs, TEST_NUMBER_OF_LEAFS);
20
    }
21
    }

Hot Tip

Mockito makes heavy use of static methods. It is good to use static imports to make code shorter and more readable. IDE can be used to automatize adding static imports.

Mockito provides a family of functions for requesting specific behaviors ring.

Method Description
thenReturn(T valueToBeReturned) Returns given value
thenThrow(Throwable toBeThrown)
thenThrow(Class<? extends Throwable>
toBeThrown)
Throws given exception
then(Answer answer)
thenAnswer(Answer answer)
Uses user-created code to
answer
thenCallRealMethod() Calls real method when working
with partial
mock/spy

Hot Tip

Non-void methods return by default an "empty" value appropriate for its type (e.g., null, 0, false, empty collection).

Following an arrange-act-assert pattern (similar to given- when-then, from Behavior Driven Development) a test should be split into three parts (blocks), each with a specified responsibility.

Section name Responsibility
arrange (given) SUT and mocks initialization and configuration
act (when) An operation which is a subject to testing;
preferably only one operation on an SUT
assert (then)

The assertion and verification phase

This way, what is being tested, is clearly separated from the setup and verification parts. To integrate cleanly with Behavior Driven Development semantics Mockito contains BDDMockito class which introduces an alias given() which can be used instead of when() method while stubbing. Here's the previous example, but now using the BDD semantics:

16
1
import static org.mockito.BDDMockito.given;
2
    import static org.mockito.Mockito.mock;
3
    import static org.testng.Assert.assertEquals;
4
​
5
    @Test
6
    public void shouldReturnGivenValueUsingBDDSemantics() {
7
    //given
8
    Flower flowerMock = mock(Flower.class);
9
    given(flowerMock.getNumberOfLeafs()).willReturn(TEST_NUMBER_OF_LEAFS);
10
​
11
    //when
12
    int numberOfLeafs = flowerMock.getNumberOfLeafs();
13
​
14
    //then
15
    assertEquals(numberOfLeafs, TEST_NUMBER_OF_LEAFS);
16
    }

given-when-then comments make intentions of tests clearer.

Section 5

Argument Matching

Mockito, by default, compares arguments using equals () methods. Sometimes it's convenient to know exactly what parameter the method will be called with.

11
1
@Test
2
    public void shouldMatchSimpleArgument() {
3
    WateringScheduler schedulerMock = mock(WateringScheduler.class);
4
    given(schedulerMock.getNumberOfPlantsScheduledOnDate(WANTED_DATE)).willReturn(VALUE_FOR_WANTED_ARGUMENT);
5
​
6
    int numberForWantedArgument = schedulerMock.getNumberOfPlantsScheduledOnDate(WANTED_DATE);
7
    int numberForAnyOtherArgument = schedulerMock.getNumberOfPlantsScheduledOnDate(ANY_OTHER_DATE);
8
​
9
    assertEquals(numberForWantedArgument, VALUE_FOR_WANTED_ARGUMENT);
10
    assertEquals(numberForAnyOtherArgument, 0);  //default value for int
11
    }

Very often we needed to define a wider matching range. Mockito provides a set of build-in matchers defined in Matchers and AdditionalMatchers classes (see corresponding table).

Hot Tip

If an argument matcher is used for at least one argument, all arguments must be provided by matchers.
3
1
given(plantSearcherMock.smellyMethod(anyInt(), contains("asparag"), eq("red"))).willReturn(true);
2
    //given(plantSearcherMock.smellyMethod(anyInt(), contains("asparag"), "red")).willReturn(true);
3
    //incorrect - would throw an exception

Luckily, in the last case, Mockito will protest by throwing a meaningful exception:

12
1
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
2
    Invalid use of argument matchers!
3
    3 matchers expected, 2 recorded.
4
    This exception may occur if matchers are combined with raw values:
5
    //incorrect:
6
    someMethod(anyObject(), "raw String");
7
    When using matchers, all arguments have to be provided by matchers.
8
    For example:
9
    //correct:
10
    someMethod(anyObject(), eq("String by matcher"));
11
​
12
    For more info see javadoc for Matchers class.

Hot Tip

The methods from the any() family don't do any type checks. Various variants were created to avoid casting. To perform type checks, method isA(Class) should be used.

It is also possible to create a custom matcher by extending the ArgumentMatcher class and using it together with argThat ()

18
1
given(schedulerMock.getNumberOfPlantsScheduledOnDate(
2
    argThat(haveHourFieldEqualTo(7)))).willReturn(1);
3
​
4
    //with the util method to create a matcher
5
    private ArgumentMatcher
6
​
7
    haveHourFieldEqualTo(final int hour) {
8
        return new ArgumentMatcher
9
​
10
    () {
11
            @Override
12
            public boolean matches(Object argument) {
13
            return ((Date) argument).getHours() == hour;
14
            }
15
            };
16
            }
17
​
18
​
Name Matching Rules
any(), any(Class<T> clazz) any object or null, the same in a
form which allows to avoid casting
anyBoolean(), anyByte(), anyChar(),
anyDouble(), anyFloat(), anyInt(),
anyLong(), anyShort(), anyString()
any object of the given type or
null - preferred over generic
any(Class<T> } clazz) for
supported types
anyCollection(), anyList(),anyMap(),
anySet()
respectively any collection type
anyCollectionOf(Class<T>
clazz), anyListOf(Class<T> clazz),
anyMapOf(Class<T> clazz),
anySetOf(Class<T> clazz)
respectively any collection type in
a generic friendly way
anyVararg() Any vararg
eq(T value) Any object that is equal to the
given using equals() method
isNull, isNull(Class<T> clazz) Null value
isNotNull, isNotNull(Class<T>
clazz)
Not null value
isA(Class<T> clazz) Any object that implements the
given class
refEq(T value, String...
excludeFields)
Any object that is equal to the
given using reflection; some fields
can be excluded
matches(String regex) String that matches the given
regular expression
startsWith(string),
endsWith(string), contains(string)
for a String class
string that starts with, ends with or
contains the given string
aryEq(PrimitiveType value[]),
aryEq(T[]
value)
an array that is equal to the given
array (has the same length and
each element is equal)
cmpEq(Comparable<T> value) any object that is equal to the
given using compareTo() method
gt(value), geq(value), lt(value),
leq(value) for primitive types and
Comparable<T>
any argument greater, greater or
equal, less, less or equal than the
given value
argThat(org.hamcrest.Matcher<T>
matcher)
any object that satisfies the
custom matching
booleanThat(Matcher<Boolean>
matcher),
byteThat(matcher),
charThat(matcher),
doubleThat(matcher),
floatThat(matcher),
intThat(matcher),
longThat(matcher),
shortThat(matcher)
any object of the given type
that satisfies the custom
matching - preferred overgeneric
argThat(matcher) for primitivesspy
and(first, second), or(first, second),
not(first) for primitive types and T
extending Object
an ability to combine results of the
other matchers

Table 1: Selected Mockito matchers

Section 6

Stubbing Multiple Calls to the Same Method

Sometimes you want to return different values for subsequent calls of the same method. Returned values can be mixed with exceptions. The last value/behavior is used for all following calls.

9
1
@Test
2
    public void shouldReturnLastDefinedValueConsistently() {
3
    WaterSource waterSource = mock(WaterSource.class);
4
    given(waterSource.getWaterPressure()).willReturn(3, 5);
5
​
6
    assertEquals(waterSource.getWaterPressure(), 3);
7
    assertEquals(waterSource.getWaterPressure(), 5);
8
    assertEquals(waterSource.getWaterPressure(), 5);
9
    }
Section 7

Stubbing Void Methods

As we've seen before, the stubbed method is passed as a parameter to a given / when method. This obviously means that you cannot use this construct for void methods. Instead, you should use willXXX..given or doXXX..when. See here:

10
1
@Test(expectedExceptions = WaterException.class)
2
    public void shouldStubVoidMethod() {
3
    WaterSource waterSourceMock = mock(WaterSource.class);
4
    doThrow(WaterException.class).when(waterSourceMock).doSelfCheck();
5
    //the same with BDD semantics
6
    //willThrow(WaterException.class).given(waterSourceMock).doSelfCheck();
7
​
8
    waterSourceMock.doSelfCheck();
9
    //exception expected
10
    }

do/willXXX methods family:

Method Description
doThrow(Throwable toBeThrown)
doThrow(Class<? extends
Throwable> toBeThrown)
Throws given exception
doAnswer(Answer answer) Uses user-created code to answer
doCallRealMethod() Working with spy
doNothing() Does nothing
doReturn(Object toBeReturned) Returns given value (not for void
methods)

will/doXXX methods are also handy when working with spy objects, as will be seen in the following section.

A given / when construct allows Mockito to internally use the type returned by a stubbed method to provide a typed argument in the will/ thenReturn methods. Void is not a valid type of it causes a compilation error. Will/doReturn does not use that trick. Will/doReturn can be also used for stubbing non-void methods, though it is not recommended because it cannot detect wrong return method types at a compilation time (only an exception at runtime will be thrown).

Hot Tip

It is not recommended to use do/ willReturn for stubbing non-void methods.
5
1
//compilation error - int expected, not boolean
2
    //given(flowerMock.getNumberOfLeafs()).willReturn(true);
3
​
4
    //only runtime exception
5
    willReturn(true).given(flowerMock).getNumberOfLeafs();
Section 8

Stubbing with a Custom Answer

In some rare cases it can be useful to implement a custom logic, later used on a stubbed method invocation. Mockito contains a generic Answer interface allowing the implementation of a callback method and providing access to invocation parameters (used arguments, a called method, and a mock instance).

23
1
@Test
2
    public void shouldReturnTheSameValue() {
3
    FlowerFilter filterMock = mock(FlowerFilter.class);
4
    given(filterMock.filterNoOfFlowers(anyInt())).will(returnFirstArgument());
5
​
6
    int filteredNoOfFlowers = filterMock.filterNoOfFlowers(TEST_NUMBER_OF_FLOWERS);
7
​
8
    assertEquals(filteredNoOfFlowers, TEST_NUMBER_OF_FLOWERS);
9
    }
10
    //reusable answer class
11
    public class ReturnFirstArgument implements Answer<Object> {
12
    @Override
13
    public Object answer(InvocationOnMock invocation) throws Throwable {
14
    Object[] arguments = invocation.getArguments();
15
    if (arguments.length == 0) {
16
    throw new MockitoException("...");
17
    }
18
    return arguments[0];
19
    }
20
    public static ReturnFirstArgument returnFirstArgument() {
21
    return new ReturnFirstArgument();
22
    }
23
    }

Warning: The need to use a custom answer may indicate that tested code is too complicated and should be re-factored.

Section 9

Verifying Behavior

Once created, a mock remembers all operations performed on it. Important from the SUT perspective, these operations can easily be verified. In the basic form, use Mockito. verify (T mock) on the mocked method.

5
1
WaterSourcewaterSourceMock=mock(WaterSource.class);
2
​
3
    waterSourceMock.doSelfCheck();
4
​
5
    verify(waterSourceMock).doSelfCheck();

By default, Mockito checks if a given method (with given arguments) was called once and only once. This can be modified using a VerificationMode. Mockito provides the number of very meaningful verification modes. It is also possible to create a custom verification mode.

Name Verifying Method was...
times(int wantedNumberOfInvocations) called exactly n times (one by default)fl
never() never called
atLeastOnce() called at least once
atLeast(int minNumberOfInvocations)

called at least n times

atMost(int maxNumberOfInvocations)

called at most n times

only()

the only method called on a mock

timeout(int millis)

interacted in a specified time range

3
1
verify(waterSourceMock,never()).doSelfCheck();
2
    verify(waterSourceMock,times(2)).getWaterPressure();
3
    verify(waterSourceMock,atLeast(1)).getWaterTemperature();

As an alternative to never (), which works only for the specified call, verifyZeroInteractions ( Object ... mocks) method can be used to verify no interaction with any method of the given mock(s). Additionally, there is one more method available, called verifyNoMoreInteractions ( Object ... mocks), which allows to ensure that no more interaction (except the already verified ones) was performed with the mock(s).verifyNoMoreInteractions can be useful in some cases, but shouldn't be overused by using on all mocks in every test. Unlike other mocking frameworks, Mockito does not automatically verify all stubbed calls. It is possible to do it manually, but usually it is just redundant. The tested code should mainly care about values returned by stubbed methods. If a stubbed method was not called, while being important from the test perspective, something else should break in a test. Mockito's philosophy allows the test writer to focus on interesting behaviors in the test for the SUT and his collaborators.

Hot Tip

Mockito does not automatically verify calls.
Section 10

Verifying Call Order

Mockito enables you to verify if interactions with a mock were performed in a given order using the InOrder API. It is possible to create a group of mocks and verify the call order of all calls within that group.

14
1
@Test
2
    publicvoidshouldVerifyInOrderThroughDifferentMocks(){
3
    WaterSourcewaterSource1=mock(WaterSource.class);
4
    WaterSourcewaterSource2=mock(WaterSource.class);
5
​
6
    waterSource1.doSelfCheck();
7
    waterSource2.getWaterPressure();
8
    waterSource1.getWaterTemperature();
9
​
10
    InOrderinOrder=inOrder(waterSource1,waterSource2);
11
    inOrder.verify(waterSource1).doSelfCheck();
12
    inOrder.verify(waterSource2).getWaterPressure();
13
    inOrder.verify(waterSource1).getWaterTemperature();
14
    }

Warning: The need to use a custom answer may indicate that tested code is too complicated and should be re-factored.

Section 11

Verifying with Argument Matching

During a verification of an interaction, Mockito uses equals () methods on the passed arguments. This is usually enough. It is a l s o possible to use the standard matchers, described earlier about stubbing, as well as custom matchers. However, in some situations it may be helpful to keep the actual argument value to make custom assertions on it. Mockito offers an ArgumentCaptor class, enabling us to retrieve the argument passed to a mock.

11
1
//when
2
    flowerSearcherMock.findMatching(searchCriteria);
3
​
4
    //then
5
    ArgumentCaptor<SearchCriteria>captor=ArgumentCaptor.
6
    forClass(SearchCriteria.class);
7
    Verify(flowerSearcherMock).findMatching(captor.capture()
8
    );
9
    SearchCriteriausedSearchCriteria=captor.getValue();s
10
    assertEquals(usedSearchCriteria.getColor(),"yellow");s
11
    assertEquals(usedSearchCriteria.getNumberOfBuds(),3);

ArgumentCaptor can be also created using @Captor annotation (see appropriate section with annotations).

Warning: It is recommended to use ArgumentCaptor with verification, but not with stubbing. Creating and using a captor in two different test blocks can decrease test readability. In addition to a situation when a stubbed method is not called, no argument is captured, which can be confusing.

Hot Tip

It is possible to retrieve arguments of all calls of a given method using captor . getAllValues ().

Warning: When an SUT internally uses the same object reference for multiple calls on a mock, every time changing its internal state (e.g., adding elements to the same list) captor . getAllValues () will return the same object in a state for the last call.

Section 12

Verifying with Timeout

Mockito lets you verify interactions within a specified time frame. It causes a verify() method to wait for a specified period of time for a requested interaction rather than fail immediately if that had not already happened. It can be useful while testing multi-threaded systems.

16
1
@Test
2
    publicvoidshouldFailForLateCall(){
3
    WaterSourcewaterSourceMock=mock(WaterSource.class);
4
    Threadt=waitAndCallSelfCheck(40,waterSourceMock);
5
​
6
    t.start();
7
​
8
    verify(waterSourceMock,never()).doSelfCheck();
9
    try{
10
    verify(waterSourceMock,timeout(20)).doSelfCheck();
11
    fail("verificationshouldfail");
12
    }catch(MockitoAssertionErrore){
13
    //expected
14
    }
15
    }
16
​

Warning: Currently, verifying with timeout doesn't work with inOrder verification.

Warning: All the multi-thread tests can become non-deterministic (e.g., under heavy load).

Section 13

Spying on Real Objects

With Mockito, you can use real objects instead of mocks by replacing only some of their methods with the stubbed ones. Usually there is no reason to spy on real objects, and it can be a sign of a code smell, but in some situations (like working with legacy code and IoC containers) it allows us to test things impossible to test with pure mocks.

13
1
@Test
2
    publicvoidshouldStubMethodAndCallRealNotStubbedMethod(){
3
    FlowerrealFlower=newFlower();
4
    realFlower.setNumberOfLeafs(ORIGINAL_NUMBER_OF_LEAFS);
5
    FlowerflowerSpy=spy(realFlower);
6
    willDoNothing().given(flowerSpy).setNumberOfLeafs(anyInt());
7
​
8
    flowerSpy.setNumberOfLeafs(NEW_NUMBER_OF_LEAFS);//stubbed‚àíshoulddonothing
9
​
10
    verify(flowerSpy).setNumberOfLeafs(NEW_NUMBER_OF_LEAFS);
11
    assertEquals(flowerSpy.getNumberOfLeafs(),ORIGINAL_NUMBER_OF_LEAFS);//valuewasnot
12
    changed
13
    }

Hot Tip

When working with spies it is required to use the willXXX..given/ doXXX..when methods family instead of given .. willXXX/when.. thenXXX. This prevents unnecessary calls to a real method during stubbing.

Warning: While spying, Mockito creates a copy of a real object, and therefore all interactions should be passed using the created spy.

Section 14

Annotations

Mockito offers three annotations–@Mock, @Spy, @Captor– to simplify the process of creating relevant objects using static methods. @InjectMocks annotation simplifies mock and spy injection. It can inject objects using constructor injection, setter injection or field injection.

24
1
//with constructor: PlantWaterer(WaterSource waterSource,
2
    // WateringScheduler wateringScheduler) {...}
3
​
4
    public class MockInjectingTest {
5
    @Mock
6
    private WaterSource waterSourceMock;
7
​
8
    @Spy
9
    private WateringScheduler wateringSchedulerSpy;
10
​
11
    @InjectMocks
12
    private PlantWaterer plantWaterer;
13
​
14
    @BeforeMethod
15
    public void init() {
16
    MockitoAnnotations.initMocks(this);
17
    }
18
​
19
    @Test
20
    public void shouldInjectMocks() {
21
    assertNotNull(plantWaterer.getWaterSource());
22
    assertNotNull(plantWaterer.getWateringScheduler());
23
    }
24
    }
Annotation Responsibility
@Mock Creates a mock of a given type
@Spy Creates a spy of a given object
@Captor Creates an argument captor of a given type
@InjectMocks Creates an object of a given type and injects
mocks and spies existing in a test

Hot Tip

To get annotations to function, you need to either call MockitoAnnotations.initMocks( testClass ) (usually in a @Before method ) or use MockitoJUnit4Runner as a JUnit runner.

Hot Tip

To make a field injection with @InjectMock, Mock- ito internally uses reflection. It can be especially useful when, in the production code, dependencies are injected directly to the private fields (e.g., by an IoC framework).
Section 15

Changing the Mock Default Return Value

Mockito enables us to redefine a default value returned from non-stubbed methods

Default Answer Description
RETURNS_DEFAULTS Returns a default "empty" value (e.g.,
null, 0, false, empty collection) - used by
default
RETURNS_SMART_NULLS Creates a spy of a given object
RETURNS_MOCKS Returns a default "empty" value, but a
mock instead of null
RETURNS_DEEP_STUBS Allows for a simple deep stubbing (e.g.,
Given(ourMock.getObject().getValue()).
willReturn(s))
CALLS_REAL_METHODS Call a real method of spied object

Warning: The last three default answers should not be needed when working with well-crafted, testable code. The behavior can be configured per mock during its creation or globally for all tests using GlobalConfiguration mechanism (it helps to use RETURNS_SMART_ NULLS by default).

6
1
PlantWatererplantWatererMock=mock(PlantWaterer.class,
2
    Mockito.RETURNS_DEEP_STUBS);
3
    given(plantWatererMock.getWaterSource().getWaterPressure()).willReturn(5);
4
​
5
    @Mock(answer=Answers.RETURNS_SMART_NULLS)
6
    privatePlantWatererplantWatererMock;

Sample verbose exception received using SmartNull:

9
1
org.mockito.exceptions.verification.SmartNullPointerException:
2
    You have a NullPointerException here:
3
    -> at PlantWaterer.generateNPE(PlantWaterer.java:24)
4
    because this method call was *not* stubbed correctly:
5
    -> at PlantWaterer.generateNPE(PlantWaterer.java:24)
6
    wateringScheduler.returnNull();
7
​
8
    at PlantWaterer.generateNPE(PlantWaterer.java:24)
9
    at DefaultValuesTest.shouldReturnNicerErrorMessageOnNPE(DefaultValuesTest.java:64)

Hot Tip

Check "Beyond the Mockito Refcard" (see link below) to get a complete tutorial on how to easily configure SmartNulls for the whole project. Also, other useful information is there that's not in this Refcard.
Section 16

Resetting Mock

In some rare cases (like using a mock as a bean in an IoC container) you may need to reset a mock using the Mockito. reset (T ... mocks) static method. This causes the mock to forget all previous behavior and interactions.

Warning: In most cases, using the reset method in a test is a code smell and should be avoided. Splitting a large test into smaller ones with mocks created for each can be helpful.

Section 17

Limitations

Mockito has a few limitations worth remembering. They are generally technical restrictions, but Mockito authors believe using hacks to work around them would encourage people to write poorly testable code. Mockito cannot:

  • mock final classes
  • mock enums
  • mock final methods
  • mock static methods
  • mock private methods
  • mock hashCode() and equals()

Nevertheless, when working with a badly written legacy code, remember that some of the mentioned limitations can be mitigated using the PowerMock or JMockit libraries.

Hot Tip

PowerMock or JMockit can be used to work with code that cannot be mocked with pure Mockito.
Section 18

Further Reading

  • http://blog.solidsoft.info/mockito-docs/- official Mockito documentation (redirect to the current version)
  • http://blog.solidsoft.info/beyond-the-mockito-refcard/ - a series of articles extending information contained In this Refcard

Like This Refcard? Read More From DZone

related article thumbnail

DZone Article

Using Python Libraries in Java
related article thumbnail

DZone Article

Infrastructure as Code (IaC) Beyond the Basics
related article thumbnail

DZone Article

Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
related article thumbnail

DZone Article

Unit Testing Large Codebases: Principles, Practices, and C++ Examples
related refcard thumbnail

Free DZone Refcard

Design Patterns
related refcard thumbnail

Free DZone Refcard

Agile Patterns
related refcard thumbnail

Free DZone Refcard

Lean Software Development
related refcard thumbnail

Free DZone Refcard

Software Configuration Management Patterns

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: