1. Overview
In this tutorial, weβll illustrate the various uses of the standard static mock methods of the Mockito API.
As in other articles focused on the Mockito framework (like Mockito Verify or Mockito When/Then), the MyList class shown below will be used as the collaborator to be mocked in test cases:
public class MyList extends AbstractList<String> {
@Override
public String get(int index) {
return null;
}
@Override
public int size() {
return 1;
}
}
2. Simple Mocking
The simplest overloaded variant of the mock method is the one with a single parameter for the class to be mocked:
public static <T> T mock(Class<T> classToMock)
Weβll use this method to mock a class and set an expectation:
MyList listMock = mock(MyList.class);
when(listMock.add(anyString())).thenReturn(false);
Then weβll execute a method on the mock:
boolean added = listMock.add(randomAlphabetic(6));
The following code confirms that we invoked the add method on the mock. The invocation returns a value that matches the expectation we set before:
verify(listMock).add(anyString());
assertThat(added).isFalse();
3. Mocking With Mockβs Name
In this section, weβll cover another variant of the mock method, which is provided with an argument specifying the name of the mock:
public static <T> T mock(Class<T> classToMock, String name)
Generally speaking, the name of a mock has nothing to do with the working code. However, it may be helpful in debugging, as we use the mockβs name to track down verification errors.
To ensure the exception message thrown from an unsuccessful verification includes the provided name of a mock, weβll use assertThatThrownBy.
In the following code, weβll create a mock for the MyList class and name it myMock:
MyList listMock = mock(MyList.class, "myMock");
Then weβll set an expectation on a method of the mock and execute it:
when(listMock.add(anyString())).thenReturn(false);
listMock.add(randomAlphabetic(6));
Next, weβll call the verification inside the assertThatThrownBy and verify the instance of the exception thrown:
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
.isInstanceOf(TooFewActualInvocations.class)
Further, we can also verify the exceptionβs message that it should contain the information about the mock:
assertThatThrownBy(() -> verify(listMock, times(2)).add(anyString()))
.isInstanceOf(TooFewActualInvocations.class)
.hasMessageContaining("myMock.add");
Hereβs the thrown exceptionβs message:
org.mockito.exceptions.verification.TooLittleActualInvocations:
myMock.add(<any>);
Wanted 2 times:
at com.baeldung.mockito.MockitoMockTest
.whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)
but was 1 time:
at com.baeldung.mockito.MockitoMockTest
.whenUsingMockWithName_thenCorrect(MockitoMockTest.java:...)
As we can see, the exception message includes the mockβs name, which will be useful for finding the failure point in case of an unsuccessful verification.
4. Mocking With Answer
Here weβll demonstrate the use of a mock variant in which weβll configure the strategy for the mockβs answers to interaction at creation time. This mock methodβs signature in the Mockito documentation looks like the following:
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)
Letβs start with the definition of an implementation of the Answer interface:
class CustomAnswer implements Answer<Boolean> {
@Override
public Boolean answer(InvocationOnMock invocation) throws Throwable {
return false;
}
}
Weβll use the CustomAnswer class above for the generation of a mock:
MyList listMock = mock(MyList.class, new CustomAnswer());
If we donβt set an expectation on a method, the default answer, configured by the CustomAnswer type, will come into play. In order to prove this, weβll skip over the expectation setting step and jump to the method execution:
boolean added = listMock.add(randomAlphabetic(6));
The following verification and assertion confirm that the mock method with an Answer argument worked as expected:
verify(listMock).add(anyString());
assertThat(added).isFalse();
5. Mocking With MockSettings
The final mock method weβll cover in this article is the variant with a parameter of the MockSettings type. We use this overloaded method to provide a non-standard mock.
There are several custom settings supported by methods of the MockSettings interface, such as registering a listener for method invocations on the current mock with invocationListeners, configuring serialization with serializable, specifying the instance to spy on with spiedInstance, configuring Mockito to attempt to use a constructor when instantiating a mock with useConstructor, etc.
For convenience, weβll reuse the CustomAnswer class introduced in the previous section to create a MockSettings implementation that defines a default answer.
A MockSettings object is instantiated by a factory method:
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
Weβll use that setting object in the creation of a new mock:
MyList listMock = mock(MyList.class, customSettings);
Similar to the preceding section, weβll invoke the add method of a MyList instance, and verify that the mock method with a MockSettings argument works as expected:
boolean added = listMock.add(randomAlphabetic(6));
verify(listMock).add(anyString());
assertThat(added).isFalse();
6. Conclusion
In this article, we covered the mock method of Mockito in detail.
