Mockito Programming Model: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(139 intermediate revisions by the same user not shown)
Line 4: Line 4:


=Overview=
=Overview=
=API=
Mockito provides a fluent API to mock Java objects.
 
=Annotations=
==<tt>@Mock</tt>==
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.mock;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.example.ExternalDependency;
import com.example.ExternalDependency;
import static org.mockito.Mockito.when;


public class SomeClassTest {
public class SomeClassTest {


  private AutoCloseable mocks;
  @Mock
   private ExternalDependency mockExternalDependency;
   private ExternalDependency mockExternalDependency;


   @Before
   @Before
   public void setUp() {
   public void openMocks() {
     mockExternalDependency = mock(ExternalDependency.class);
     mocks = MockitoAnnotations.openMocks(this);
  }
 
  @After
  public void releaseMocks() throws Exception {
    mocks.close();
   }
   }


   @Test
   @Test
   public void someTest() throws Exception {
   public void someTest() throws Exception {
    when(mockExternalDependency.someMethod()).thenReturn(...);
     ...
     ...
   }
   }
}
}
</syntaxhighlight>
</syntaxhighlight>
==<tt>@Spy</tt>==
This creates a spy of a given object. It can be used instead of <code>[[#Spying_on_Real_Objects|spy(Object)]]</code>.


=Annotations=
==<tt>@Captor</tt>==
This simplifies the creation of [[#Verifying_Arguments_with_ArgumentCaptor|ArgumentCaptor]].
 
==<tt>@InjectMocks</tt>==
The annotation injects mock or spy fields into tested objects automatically using '''constructor''' injection, '''setter''' injection or '''field''' injection.
=API=
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
import org.mockito.Mock;
import static org.mockito.Mockito.mock;
import org.mockito.MockitoAnnotations;
import com.example.ExternalDependency;
import com.example.ExternalDependency;


public class SomeClassTest {
public class SomeClassTest {


  private AutoCloseable mocks;
  @Mock
   private ExternalDependency mockExternalDependency;
   private ExternalDependency mockExternalDependency;


   @Before
   @Before
   public void openMocks() {
   public void setUp() {
     mocks = MockitoAnnotations.openMocks(this);
     mockExternalDependency = mock(ExternalDependency.class);
  }
 
  @After
  public void releaseMocks() throws Exception {
    mocks.close();
   }
   }


Line 54: Line 66:
}
}
</syntaxhighlight>
</syntaxhighlight>
=<span id='Stub_Functionality'></span>Implementing Stub Functionality=
 
<font color=darkgray>How to release mocks created this way?</font>
 
=<span id='Stub_Functionality'></span><span id='Implementing_Stub_Functionality'>Implementing Stubs=
{{External|https://github.com/ovidiuf/playground/tree/master/java/mockito/annotation-stub}}
{{External|https://github.com/ovidiuf/playground/tree/master/java/mockito/annotation-stub}}
A [[Software_Testing_Concepts#Stub|stub]] returns synthetic responses or throws exceptions when its methods are invoked. Mockito supports stubbing and by returning a given value when a specific method of the [[Mockito_Concepts#Managed_Test_Double|managed test double]] is called. Mockito implements the stub functionality with <code>Mockito.when(<method>).thenReturn(...)</code> pattern:
A [[Software_Testing_Concepts#Stub|stub]] returns synthetic responses or throws exceptions when its methods are invoked. Mockito supports stubbing and by returning a given value when a specific method of the [[Mockito_Concepts#Managed_Test_Double|managed test double]] is called. Mockito implements the stub functionality with <code>Mockito.when(<method>).then*(...)</code> pattern - using this API pattern is often referred to as "setting the expectations". The synthetic response is selected based on the arguments of the call, using the arguments values themselves or [[#Argument_Matchers|argument matchers]]:
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
public class ExternalDependency {
public class ExternalDependency {
Line 65: Line 80:
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.when;
public class SomeClassTest {
public class SomeClassTest {


Line 72: Line 88:
   @Test
   @Test
   public void someTest() throws Exception {
   public void someTest() throws Exception {
     Mockito.when(mockExternalDependency.someMethod()).thenReturn("some synthetic result");
     when(mockExternalDependency.someMethod()).thenReturn("some synthetic result");
     ...
     ...
   }
   }
}
}
</syntaxhighlight>
</syntaxhighlight>
The <code>when()</code> configures the method(s) to stub, or the '''trigger action'''. The <code>then*()</code> methods specify what to do when the trigger is activated. The options are:
The <code>when()</code> configures the method(s) to stub, or the '''trigger action'''. The <code>then*()</code> methods specify what to do when the trigger is activated. Void methods are a [[#Void_Methods|special case]].
==Stub Responses==
==Void Methods==
Unit testing void methods is difficult. Conventionally, a unit test provides arguments to a method and checks the result, working with the direct output of the method. For void methods, the method presumably changes the internal state of the objects under test, to the unit test must make assertions on the indirect output of the method. A common pattern to implement this is to provide managed mocks so the void methods acts on those instead of real dependencies.
 
By default, the managed test double does nothing on void methods, so there's no need to configure anything on it. The invocation on a void method will just complete successfully. Whether the invocation was performed or not can be checked with <code>[[#Testing_Interaction_with_the_Test_Double|verify()]]</code>.
 
===<tt>doAnswer()</tt> - Executing Arbitrary Logic for Void Methods===
If we need to execute arbitrary logic when a void method is invoked, use this pattern:
<syntaxhighlight lang='java'>
doAnswer(answer).when(mockObject).<void-method-name>(arguments);
</syntaxhighlight>
<syntaxhighlight lang='java'>
doAnswer(new Answer() { ... }).when(mockExternalDependency).writeLine("....");
</syntaxhighlight>
For more details about Answer objects, see [[#Answer|Answer]] below.
 
If we need to simulate an exception that is thrown by a void method, use this pattern:
===<span id='Throwing_Exceptions_for_Void_Methods'></span><tt>toThrow()</tt> - Throwing Exceptions for Void Methods===
<syntaxhighlight lang='java'>
doThrow(exception).when(mockObject).<void-method-name>(arguments);
</syntaxhighlight>
<syntaxhighlight lang='java'>
doThrow(IOException.class).when(mockExternalDependency).writeLine("....");
</syntaxhighlight>
 
===<tt>doNothing()</tt>===
 
==<span id='Stub_Responses'></span>Stub Responses for Non-Void Methods==
The common pattern on non-void methods is:
<syntaxhighlight lang='java'>
when(mockExternalDependency.<some-method>(...)).then*(...);
</syntaxhighlight>
===<tt>thenReturn()</tt>===
===<tt>thenReturn()</tt>===
<code>thenReturn(...)</code> returns the given value. It has several variants:
<code>thenReturn(...)</code> returns the given value. It has several variants:
* <code>thenReturn(value)</code>: return the same value every time.
* <code>thenReturn(value)</code>: return the same value every time.
* <code>thenReturn(value1, value2, value3, ...)</code>: return the first value on first invocation, second value on the second invocation, etc. The equivalent is: <code>thenReturn(value1).thenReturn(value2).thenReturn(value3). ...</code>
* <code>thenReturn(value1, value2, value3, ...)</code>: return the first value on first invocation, second value on the second invocation, etc. The equivalent is: <code>thenReturn(value1).thenReturn(value2).thenReturn(value3). ...</code>
⚠️ If a builder of any kind is used as argument of <code>thenReturn()</code>, the code that builds the response is executed at the time of the mock configuration, and the result computed at configuration time is returned when the stubbed method is invoked. Do not use <code>thenReturn()</code> if the result should be dynamic and evaluated at the time of invocation. Use <code>[[#thenAnswer.28.29|thenAnswer()]]</code> instead.


===<tt>thenThrow()</tt>===
===<tt>thenThrow()</tt>===
Line 89: Line 136:
when(mockExternalDependency.someMethod()).thenThrow(IOException.class);
when(mockExternalDependency.someMethod()).thenThrow(IOException.class);
</syntaxhighlight>
</syntaxhighlight>
 
There is [[#Throwing_Exceptions_for_Void_Methods|alternative syntax]] for throwing exceptions on void methods.
Alternative syntax for throwing exceptions on methods that return <code>void</code> <font color=darkgray>Why is this necessary? Why can't we use the normal thenThrow()?</font>
===<tt>thenCallRealMethod()</tt>===
<code>thenCallRealMethod()</code> delegates the invocation to the real external dependency.
===<tt>thenAnswer()</tt>===
{{External|https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/Mockito.html#answer_stubs}}
<code>thenAnswer(Answer answer)</code> executes custom logic and compute a value to return. This turns the [[Software Testing Concepts#Stub|stub]] object into a [[Software Testing Concepts#Fake|fake]]. It uses [[#Answer|Answers]]:
====<tt>Answer</tt>====
<code>Answer</code> implementation is a callback. This is considered a somewhat controversial feature, as increases the complexity of the code. <code>[[#thenReturn()|thenReturn()]]</code> and <code>[[#thenThrow()|thenThrow()]]</code> should be used instead, if possible.
<syntaxhighlight lang='java'>
when(mock.someMethod(anyString(), anyLong())).thenAnswer((Answer<SomeResult>) invocation -> {
  String arg0 = invocation.getArgument(0);
  long arg1 = invocation.getArgument(1);
  Object[] args = i.getArguments();
  Object mock = i.getMock(); 
  if ("red".equals(arg0)) {
    return new SomeResult("RED", arg1);
  }
  return new SomeResult(arg0, arg1);
});
</syntaxhighlight>
Legacy:
<syntaxhighlight lang='java'>
when(mock.someMethod(...)).thenAnswer(new Answer() {
  public Object answer(InvocationOnMock i) {
    Object[] args = i.getArguments();
    Object mock = i.getMock(); 
    return "called with arguments: " + Arrays.toString(args);
  }
});
</syntaxhighlight>
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
doThrow(exception).when(mock).voidmethod(arguments);
when(mock.someMethod(...)).then(new Answer() { ... });
</syntaxhighlight>
</syntaxhighlight>
Also see executing arbitrary logic when void methods are invoked, [[#Void_Methods|above]].
==<span id='Argument_Matcher'></span>Argument Matchers==
The [[Software_Testing_Concepts#Test_Double|test double]] should be configured prior to running the test and programmed how to react when a method is invoked with specific arguments by using the <code>Mockito.when(...)</code> API. This is achieved using a mechanism called '''argument matchers'''. The actual arguments of the call are matched against a list of pre-configured options, and if there is a match, the matching entry is used to simulate the invocation response by returning a pre-set result, throw an exception, or trigger custom logic to compute the result.


===<tt>thenAnswer()</tt>===
The default behavior in absence of any configured argument matcher is that the method returns the default value for the return type: 0 for <code>int</code>, <code>null</code> for <code>String</code>, etc. Also see [[#Default_Behavior|Default Behavior]] below.
<code>thenAnswer(Answer answer)</code> executes custom logic and compute a value to return. This turns the [[Software Testing Concepts#Stub|stub]] object into a [[Software Testing Concepts#Fake|fake]].


===<tt>thenCallRealMethod()</tt>===
The test double can be configured to issue specific responses to a method invocation based on [[#Individual_Argument_Values|individual argument values]], predefined [[#Wildcard_Matchers|wildcard matchers]] or [[#Custom_ArgumentMatcher|custom matchers]]. When using matchers, all arguments of a method must be provided by matchers. Mixing [[#Individual_Argument_Values|individual argument values]] and wildcard matchers is not allowed. The following invocation will fail:
<code>thenCallRealMethod()</code> delegates the invocation to the real external dependency.
<syntaxhighlight lang='java'>
verify(mock).someMethod(1, anyString(), "some string");
</syntaxhighlight>
<span id='eq_usage'></span>However, this situation can be easily worked around by using the <code>[[#eq|eq(...)]]</code> in lieu of an individual value:
<syntaxhighlight lang='java'>
verify(mock).someMethod(eq(1), anyString(), eq("some string"));
</syntaxhighlight>
===Individual Argument Values===


==<span id='Argument_Matcher'></span>Argument Matchers==
===Wildcard Matchers===
===<tt>isA()</tt>===
{{External|https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html}}
Mockito wildcard marchers are static methods of the [https://github.com/mockito/mockito/blob/main/src/main/java/org/mockito/ArgumentMatchers.java org.mockito.ArgumentMatchers] class. Note that the equivalent, older <code>org.mockito.Matchers</code> has been deprecated and it should not be used.
<font size='-1'>
{| class="wikitable" style="text-align: left;"
! Matcher
! Notes
|-
| <tt>any()</tt> ||
|-
| <tt>anyObject()</tt> ||
|-
| <tt>any(Class<T> c)</tt> ||
|-
| <tt>[[#isA.28.29|isA(Class<T> c)]]</tt> || Example [[#isA.28.29|below]]
|-
| <tt>anyVararg()</tt> ||
|-
| <tt>anyBoolean()</tt> <tt>anyByte()</tt> <tt>anyChar()</tt> <span id='anyInt'></span><tt>anyInt()</tt> <tt>anyLong()</tt> <tt>anyFloat()</tt> <tt>anyDouble()</tt> <tt>anyShort()</tt> <span id='anyString'></span><tt>[[#anyString.28.29|anyString()]]</tt>  ||
|-
| <tt>anyList()</tt> <tt>anyListOf(Class<T> c)</tt> ||
|-
| <tt>anySet()</tt> <tt>anySetOf(Class<T> c)</tt>  ||
|-
| <tt>anyMap()</tt> <tt>anyMapOf(Class<K> keyC, Class<V> valueC)</tt> ||
|-
| <tt>anyCollection()</tt> <tt>anyCollectionOf(Class<T> c)</tt> ||
|-
| <tt>anyIterable()</tt> <tt>anyIterableOf(Class<T> c)</tt> ||
|-
|<span id='eq'></span><tt>[[#eq_usage|eq(T value)]]</tt>
<tt>eq(boolean value)</tt> <tt>eq(byte value)</tt> <tt>eq(char value)</tt><br> <tt>eq(double value)</tt> <tt>eq(float value)</tt> <tt>eq(int value)</tt> <br><tt>eq(long value)</tt> <tt>eq(short value)</tt>  ||
|-
| <tt>refEq(T value, String... excludeFields)</tt> ||
|-
| <tt>same(T value)</tt>||
|-
| <tt>isNull()</tt> <tt>isNull(Class<T> c)</tt> <tt>notNull()</tt> <tt>notNull(Class<T> c)</tt> <tt>isNotNull()</tt> <tt>isNotNull(Class<T> c)</tt> ||
|-
| <tt>[[#nullable.28Class.3CT.3E_c.29|nullable(Class<T> c)]]</tt> ||
|-
| <tt>contains(String substring)</tt> ||
|-
| <tt>matches(String regex)</tt> <tt>matches(String regex)</tt> ||
|-
| <tt>endsWith(String suffix)</tt> <tt>startsWith(String prefix)</tt>  ||
|-
| <tt>argThat(ArgumentMatcher<T> m)</tt> <tt>charThat(ArgumentMatcher<Character> m)</tt><br> <tt>booleanThat(ArgumentMatcher<Boolean> m)</tt> <tt>byteThat(ArgumentMatcher<Byte> m)</tt> <br><tt>shortThat(ArgumentMatcher<Short> m)</tt> <tt>intThat(ArgumentMatcher<Integer> m)</tt><br> <tt>longThat(ArgumentMatcher<Long> m)</tt> <tt>floatThat(ArgumentMatcher<Float> m)</tt> <br><tt>doubleThat(ArgumentMatcher<Double> m)</tt>||
|-
|}
</font>
====<tt>isA()</tt>====
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
public class ExternalDependency {
public class ExternalDependency {
Line 112: Line 247:
<syntaxhighlight lang='java'>
<syntaxhighlight lang='java'>
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.isA;
  ...
import static org.mockito.Mockito.when;
  Mockito.when(mockExternalDependency.someMethodWithArg(isA(String.class))).thenReturn(...);
 
}
...
when(mockExternalDependency.someMethodWithArg(isA(String.class))).thenReturn(...);
</syntaxhighlight>
</syntaxhighlight>
<font color=darkgray>Why is isA() needed, why not provide the class, directly?</font>
<font color=darkgray>Why is isA() needed, why not provide the class, directly?</font>
===<tt>anyString()</tt>===
====<tt>anyString()</tt>====
{{External|https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/ArgumentMatchers.html#anyString--}}
⚠️ Note that since 2.1.0, <code>anyString()</code> does not match null. To match a String or <code>null</code>, use <code>nullable(String.class)</code>.
 
====<tt>nullable(Class<T> c)</tt>====
Note that since Mockito 2.1.0, matches like <code>anyString()</code> do not match <code>null</code> values anymore. If you need a match to happen for a non-null <code>String</code> '''or''' <code>null</code>, use:
<syntaxhighlight lang='java'>
when(mock.someMethod(nullable(String.class))).thenReturn(...);
</syntaxhighlight>
 
===Custom <tt>ArgumentMatcher</tt>===
<font color=darkgray>TODO. "Working with a custom ArgumentMatcher class" section in Mockito Essentials.</font>
{{Internal|Hamcrest|Hamcrest}}
 
==Default Behavior==
Non-stubbed methods for a mock objects, as well as invocations for which there's no argument match, return default values: <code>null</code> for an Object, 0 for an integer, <code>false</code> for a boolean.
 
This behavior can be changed by configuring Mockito with the following options:
* RETURNS_DEFAULTS. The default behavior.
* RETURNS_SMART_NULLS. Return stubs that act like nulls, in that they throw exceptions if a method is attempted to be called on them. The exceptions are more useful that the normal <code>NullPointerException</code> behavior.
* RETURNS_MOCKS. Return mocks for objects and default values for primitives.
* RETURNS_DEEP_STUBS.
* CALL_REAL_METHODS.
==Determining whether a Test Double is a Mock==
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.mockingDetails;
mockingDetails(mockObject).isMock();
</syntaxhighlight>
 
=<span id='Implementing_Spys'></span><span id='Implementing_Spies'></span>Implementing Spies=
==Testing Interaction with the Test Double==
===Number of Invocations===
{{External|https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#exact_verification}}
Many times during testing it is useful to know if our mocked external dependency was called into with a specific method, or any method, how many times per method, and so on. Mockito exposes API for this in form of the <code>Mockito.verify(...)</code> set of methods. The mock object should be declared and configured as described in the [[#Annotations|Annotations]] section. Then the number of invocations of certain methods, or whether the methods have been invoked at all, can be tested with:
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.verify;
...
verify(mock).someMethod("some argument");
</syntaxhighlight>
This invocation succeeds if the method <code>someMethod()</code> was invoked with the argument <code>"some argument"</code> once and only once. The invocation is equivalent with:
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
...
verify(mock, times(1)).someMethod("some argument");
</syntaxhighlight>
 
Other options:
<syntaxhighlight lang='java'>
verify(mock, never()).someMethod("some argument");
verify(mock, atMostOnce()).someMethod("some argument");
verify(mock, atLeastOnce()).someMethod("some argument");
verify(mock, atLeast(2)).someMethod("some argument");
verify(mock, atMost(5)).someMethod("some argument");
verify(mock, only()).someMethod("some argument");
</syntaxhighlight>
===Mock-wide Interactions===
{{External|https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/Mockito.html#never_verification}}
<syntaxhighlight lang='java'>
verifyZeroInteractions(mockOne, mockTwo);
verifyNoMoreInteractions(mock);
</syntaxhighlight>
===Invocation Order===
<font color=darkgray>TODO Mockito Essentials "Verifying an invocation order".</font>
===Verifying Arguments with <tt>ArgumentCaptor</tt>===
<font color=darkgray>TODO Mockito Essentials "Verifying arguments using ArgumentCaptor".
 
Generic collection arguments.
 
Variable arguments and arrays.
 
Also see [[#.40Captor|@Captor]]
</font>
 
==Spying on Real Objects==
<font color=darkgray>TODO Mockito Essentials "Spying Objects".
 
<code>spy(Object)</code>. Also see [[#.40Spy|@Spy]]
 
</font>
==Determining whether a Test Double is a Spy==
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.mockingDetails;
mockingDetails(testDoubleObject).isSpy();
</syntaxhighlight>
 
=Resetting Mock Objects=
A mock object can be reset via API.
<syntaxhighlight lang='java'>
import static org.mockito.Mockito.reset;
...
reset(mockObject);
</syntaxhighlight>
=Troubleshooting=
* No configured invocation matches the current invocation. The configured invocation is declared with an int argument, and the invocation is made with a long.

Latest revision as of 00:33, 3 September 2021

Internal

Overview

Mockito provides a fluent API to mock Java objects.

Annotations

@Mock

import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.example.ExternalDependency;
import static org.mockito.Mockito.when;

public class SomeClassTest {

  private AutoCloseable mocks;

  @Mock
  private ExternalDependency mockExternalDependency;

  @Before
  public void openMocks() {
    mocks = MockitoAnnotations.openMocks(this);
  }

  @After
  public void releaseMocks() throws Exception {
    mocks.close();
  }

  @Test
  public void someTest() throws Exception {
    when(mockExternalDependency.someMethod()).thenReturn(...);
    ...
  }
}

@Spy

This creates a spy of a given object. It can be used instead of spy(Object).

@Captor

This simplifies the creation of ArgumentCaptor.

@InjectMocks

The annotation injects mock or spy fields into tested objects automatically using constructor injection, setter injection or field injection.

API

import static org.mockito.Mockito.mock;
import com.example.ExternalDependency;

public class SomeClassTest {

  private ExternalDependency mockExternalDependency;

  @Before
  public void setUp() {
    mockExternalDependency = mock(ExternalDependency.class);
  }

  @Test
  public void someTest() throws Exception {
    ...
  }
}

How to release mocks created this way?

Implementing Stubs

https://github.com/ovidiuf/playground/tree/master/java/mockito/annotation-stub

A stub returns synthetic responses or throws exceptions when its methods are invoked. Mockito supports stubbing and by returning a given value when a specific method of the managed test double is called. Mockito implements the stub functionality with Mockito.when(<method>).then*(...) pattern - using this API pattern is often referred to as "setting the expectations". The synthetic response is selected based on the arguments of the call, using the arguments values themselves or argument matchers:

public class ExternalDependency {
  public String someMethod() {
    ...
  }
}
import static org.mockito.Mockito.when;
public class SomeClassTest {

  @Mock
  private ExternalDependency mockExternalDependency;

  @Test
  public void someTest() throws Exception {
    when(mockExternalDependency.someMethod()).thenReturn("some synthetic result");
    ...
  }
}

The when() configures the method(s) to stub, or the trigger action. The then*() methods specify what to do when the trigger is activated. Void methods are a special case.

Void Methods

Unit testing void methods is difficult. Conventionally, a unit test provides arguments to a method and checks the result, working with the direct output of the method. For void methods, the method presumably changes the internal state of the objects under test, to the unit test must make assertions on the indirect output of the method. A common pattern to implement this is to provide managed mocks so the void methods acts on those instead of real dependencies.

By default, the managed test double does nothing on void methods, so there's no need to configure anything on it. The invocation on a void method will just complete successfully. Whether the invocation was performed or not can be checked with verify().

doAnswer() - Executing Arbitrary Logic for Void Methods

If we need to execute arbitrary logic when a void method is invoked, use this pattern:

doAnswer(answer).when(mockObject).<void-method-name>(arguments);
doAnswer(new Answer() { ... }).when(mockExternalDependency).writeLine("....");

For more details about Answer objects, see Answer below.

If we need to simulate an exception that is thrown by a void method, use this pattern:

toThrow() - Throwing Exceptions for Void Methods

doThrow(exception).when(mockObject).<void-method-name>(arguments);
doThrow(IOException.class).when(mockExternalDependency).writeLine("....");

doNothing()

Stub Responses for Non-Void Methods

The common pattern on non-void methods is:

when(mockExternalDependency.<some-method>(...)).then*(...);

thenReturn()

thenReturn(...) returns the given value. It has several variants:

  • thenReturn(value): return the same value every time.
  • thenReturn(value1, value2, value3, ...): return the first value on first invocation, second value on the second invocation, etc. The equivalent is: thenReturn(value1).thenReturn(value2).thenReturn(value3). ...

⚠️ If a builder of any kind is used as argument of thenReturn(), the code that builds the response is executed at the time of the mock configuration, and the result computed at configuration time is returned when the stubbed method is invoked. Do not use thenReturn() if the result should be dynamic and evaluated at the time of invocation. Use thenAnswer() instead.

thenThrow()

thenThrow(Throwable) throws the given exception. This can be used together with JUnit feature that provides syntactic support for tests that are supposed to check exceptions (@Test(expected = <exception-class>)).

when(mockExternalDependency.someMethod()).thenThrow(IOException.class);

There is alternative syntax for throwing exceptions on void methods.

thenCallRealMethod()

thenCallRealMethod() delegates the invocation to the real external dependency.

thenAnswer()

https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/Mockito.html#answer_stubs

thenAnswer(Answer answer) executes custom logic and compute a value to return. This turns the stub object into a fake. It uses Answers:

Answer

Answer implementation is a callback. This is considered a somewhat controversial feature, as increases the complexity of the code. thenReturn() and thenThrow() should be used instead, if possible.

when(mock.someMethod(anyString(), anyLong())).thenAnswer((Answer<SomeResult>) invocation -> {
  String arg0 = invocation.getArgument(0);
  long arg1 = invocation.getArgument(1);
  Object[] args = i.getArguments();
  Object mock = i.getMock();  
  if ("red".equals(arg0)) {
    return new SomeResult("RED", arg1);
  }
  return new SomeResult(arg0, arg1);
});

Legacy:

when(mock.someMethod(...)).thenAnswer(new Answer() {
  public Object answer(InvocationOnMock i) {
    Object[] args = i.getArguments();
    Object mock = i.getMock();   
    return "called with arguments: " + Arrays.toString(args);
  }
});
when(mock.someMethod(...)).then(new Answer() { ... });

Also see executing arbitrary logic when void methods are invoked, above.

Argument Matchers

The test double should be configured prior to running the test and programmed how to react when a method is invoked with specific arguments by using the Mockito.when(...) API. This is achieved using a mechanism called argument matchers. The actual arguments of the call are matched against a list of pre-configured options, and if there is a match, the matching entry is used to simulate the invocation response by returning a pre-set result, throw an exception, or trigger custom logic to compute the result.

The default behavior in absence of any configured argument matcher is that the method returns the default value for the return type: 0 for int, null for String, etc. Also see Default Behavior below.

The test double can be configured to issue specific responses to a method invocation based on individual argument values, predefined wildcard matchers or custom matchers. When using matchers, all arguments of a method must be provided by matchers. Mixing individual argument values and wildcard matchers is not allowed. The following invocation will fail:

verify(mock).someMethod(1, anyString(), "some string");

However, this situation can be easily worked around by using the eq(...) in lieu of an individual value:

verify(mock).someMethod(eq(1), anyString(), eq("some string"));

Individual Argument Values

Wildcard Matchers

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/ArgumentMatchers.html

Mockito wildcard marchers are static methods of the org.mockito.ArgumentMatchers class. Note that the equivalent, older org.mockito.Matchers has been deprecated and it should not be used.

Matcher Notes
any()
anyObject()
any(Class<T> c)
isA(Class<T> c) Example below
anyVararg()
anyBoolean() anyByte() anyChar() anyInt() anyLong() anyFloat() anyDouble() anyShort() anyString()
anyList() anyListOf(Class<T> c)
anySet() anySetOf(Class<T> c)
anyMap() anyMapOf(Class<K> keyC, Class<V> valueC)
anyCollection() anyCollectionOf(Class<T> c)
anyIterable() anyIterableOf(Class<T> c)
eq(T value)

eq(boolean value) eq(byte value) eq(char value)
eq(double value) eq(float value) eq(int value)
eq(long value) eq(short value) ||

refEq(T value, String... excludeFields)
same(T value)
isNull() isNull(Class<T> c) notNull() notNull(Class<T> c) isNotNull() isNotNull(Class<T> c)
nullable(Class<T> c)
contains(String substring)
matches(String regex) matches(String regex)
endsWith(String suffix) startsWith(String prefix)
argThat(ArgumentMatcher<T> m) charThat(ArgumentMatcher<Character> m)
booleanThat(ArgumentMatcher<Boolean> m) byteThat(ArgumentMatcher<Byte> m)
shortThat(ArgumentMatcher<Short> m) intThat(ArgumentMatcher<Integer> m)
longThat(ArgumentMatcher<Long> m) floatThat(ArgumentMatcher<Float> m)
doubleThat(ArgumentMatcher<Double> m)

isA()

public class ExternalDependency {
  public String someMethodWithArg(String s) {
    ...
  }
}
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.when;

...
when(mockExternalDependency.someMethodWithArg(isA(String.class))).thenReturn(...);

Why is isA() needed, why not provide the class, directly?

anyString()

https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/ArgumentMatchers.html#anyString--

⚠️ Note that since 2.1.0, anyString() does not match null. To match a String or null, use nullable(String.class).

nullable(Class<T> c)

Note that since Mockito 2.1.0, matches like anyString() do not match null values anymore. If you need a match to happen for a non-null String or null, use:

when(mock.someMethod(nullable(String.class))).thenReturn(...);

Custom ArgumentMatcher

TODO. "Working with a custom ArgumentMatcher class" section in Mockito Essentials.

Hamcrest

Default Behavior

Non-stubbed methods for a mock objects, as well as invocations for which there's no argument match, return default values: null for an Object, 0 for an integer, false for a boolean.

This behavior can be changed by configuring Mockito with the following options:

  • RETURNS_DEFAULTS. The default behavior.
  • RETURNS_SMART_NULLS. Return stubs that act like nulls, in that they throw exceptions if a method is attempted to be called on them. The exceptions are more useful that the normal NullPointerException behavior.
  • RETURNS_MOCKS. Return mocks for objects and default values for primitives.
  • RETURNS_DEEP_STUBS.
  • CALL_REAL_METHODS.

Determining whether a Test Double is a Mock

import static org.mockito.Mockito.mockingDetails;
mockingDetails(mockObject).isMock();

Implementing Spies

Testing Interaction with the Test Double

Number of Invocations

https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#exact_verification

Many times during testing it is useful to know if our mocked external dependency was called into with a specific method, or any method, how many times per method, and so on. Mockito exposes API for this in form of the Mockito.verify(...) set of methods. The mock object should be declared and configured as described in the Annotations section. Then the number of invocations of certain methods, or whether the methods have been invoked at all, can be tested with:

import static org.mockito.Mockito.verify;
...
verify(mock).someMethod("some argument");

This invocation succeeds if the method someMethod() was invoked with the argument "some argument" once and only once. The invocation is equivalent with:

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;
...
verify(mock, times(1)).someMethod("some argument");

Other options:

verify(mock, never()).someMethod("some argument");
verify(mock, atMostOnce()).someMethod("some argument");
verify(mock, atLeastOnce()).someMethod("some argument");
verify(mock, atLeast(2)).someMethod("some argument");
verify(mock, atMost(5)).someMethod("some argument");
verify(mock, only()).someMethod("some argument");

Mock-wide Interactions

https://javadoc.io/static/org.mockito/mockito-core/3.11.2/org/mockito/Mockito.html#never_verification
verifyZeroInteractions(mockOne, mockTwo);
verifyNoMoreInteractions(mock);

Invocation Order

TODO Mockito Essentials "Verifying an invocation order".

Verifying Arguments with ArgumentCaptor

TODO Mockito Essentials "Verifying arguments using ArgumentCaptor".

Generic collection arguments.

Variable arguments and arrays.

Also see @Captor

Spying on Real Objects

TODO Mockito Essentials "Spying Objects".

spy(Object). Also see @Spy

Determining whether a Test Double is a Spy

import static org.mockito.Mockito.mockingDetails;
mockingDetails(testDoubleObject).isSpy();

Resetting Mock Objects

A mock object can be reset via API.

import static org.mockito.Mockito.reset;
...
reset(mockObject);

Troubleshooting

  • No configured invocation matches the current invocation. The configured invocation is declared with an int argument, and the invocation is made with a long.