Use Mockito with Spring

In Mockito Answer, we mock the process.

Why Mockito

Unit tests are to test behaviours with initialling the real objects or load the real dependencies. Mocks and stubs are fake Java classes that replace these external dependencies. Stubs have hardcoded logic. Mockito is the most popular Mocking framework for unit tests written in Java.

Common targets for mocking are:

  • Database connections,
  • Web services,
  • Slow classes,
  • Classes with side effects, and
  • Classes with non-deterministic behaviour.

How to mock a behaviour

  1. Before method run, you tell Mockito what to do when methods got called
  2. While method run, mock instance run without dependencies
  3. After method run, you verify the result

Mockito offers two ways of stubbing.

  1. when this method is called, then do something
  2. Do something when this mock’s method is called with the given arguments

The first way is considered preferred because

  • it is typesafe and
  • readable.

However, you’re forced to use the second way, such as when stubbing a real method of a spy because calling it may have unwanted side effects.

Enable Mockito annotations

With jUnit 4

Two ways

  1. Annotate the JUnit testing class

    Mockito runner initializes proxy objects annotated with the @Mock annotation.

    public class MockitoAnnotationTest {}
  2. Initialise it inside of @Before

    public void init() {

With jUnit 5

class MockitoAnnotationTest {}


  • @Mock creates and injects mocked instances. It equals to Mockito.mock.
  • @Spy spy the behavious (in order to verify them).
  • Captor to create an ArgumentCaptor instance.
  • @InjectMocks to inject mock fields into the tested object automatically.
  • @MockBean uses in Spring Boot. We use it to add mock objects to the Spring application context. The mock will replace any existing bean of the same type in the application context. It’s useful when you need to mock an external service.

1. @Mock

  • Without @Mock

    public void testWithoutMockAnnotation() {
        List mockList = Mockito.mock(ArrayList.class);
  • With @Mock

    @Mock List<String> mockedList;
    public void testWithMockAnnotation() {

2. @Spy

  • Without @Spy

    public void testWithoutSpyAnnotation() {
        List<String> spyList = Mockito.spy(new ArrayList<String>());
  • With @Spy

    @Spy List<String> spiedList = new ArrayList<String>();
    public void testWithSpyAnnotation() {

3. @Captor

  • Without @Captor

    public void testWithoutCaptorAnnotation() {
        List mockList = Mockito.mock(List.class);
        ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
        assertEquals("one", arg.getValue());
  • With @Captor

    @Mock List mockedList;
    @Captor ArgumentCaptor argCaptor;
    public void testWithCaptorAnnotation() {
        assertEquals("one", argCaptor.getValue());

4. @InjectMocks

It’s used to instantiate the @InjectMock annotated field and inject all the @Mock or @Spy annotated fields into it (if applicable).

All 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).

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).

5. @MockBean

The @MockBean will also be injected into the field.

public class MockBeanAnnotationIntegrationTest {

    UserRepository mockUserRepository;

    public void givenCountMethodMocked_WhenCountInvoked_ThenMockValueReturned() {
            .thenReturn(new Something());


  1. When… Then

           invocation -> invocation.getArgument(0) + "!");
    when(passwordEncoder.encode("1")).thenAnswer(invocation -> {
       throw new IllegalArgumentException();
    // throw exception instance
      .thenThrow(new IllegalArgumentException());
    // throw exception class
  2. Do… When

    doAnswer(invocation -> invocation.getArgument(0) + "!")
    doThrow(new IllegalArgumentException()).when(passwordEncoder).encode("1");

Argument Matchers

  • eq() //todo

Mock a void method

Mock a single saving

Saving a new User object, means service accept a user without Id and will return a user with id to the front end. When we mockito it, we would do it this way:

when( Answer<String>() {
    public User answer(InvocationOnMock invocation) throws Throwable {
        User user = (User)invocation.getArguments()[0];
        return user;

Mock a batch saving

In order to improve performance, we sometimes like to use saveAll() method. So this time we pass in a list of Users, here is the answer:

    .thenAnswer(new Answer<List<User>>() {
        public List<User> answer(InvocationOnMock invocation) throws Throwable {
            List<User> users = (List)invocation.getArguments()[0];

            User user = users
                    .filter(user -> user.getId() == null)

            return users;

Handle expected exception

when(myMock.doSomething()).thenThrow(new MyException());
public ExpectedException expectedException = ExpectedException.none();

public void testExceptionMessage() throws Exception {
    expectedException.expectMessage("The expected message");

    given( AnyException("The expected message"));



What Mockito cannot do

Mockito cannot mock or spy on:

  • Java constructs such as final classes and methods
  • static methods,
  • enums,
  • private methods (with Spring ReflectionTestUtils)
  • the equals() and hashCode() methods,
  • primitive types, and
  • anonymous classes.

Answer to this:

  • PowerMockito, an extension of the Mockito, let us mock static and private methods.
  • As per the design, you should not opt for mocking private or static properties because it violates the encapsulation.
  • You should refactor the offending code to make it testable.

Mockito mock private methods using RelectionTestUtils

The org.springframework.test.util package contains ReflectionTestUtils, which is a collection of relection-based utility methods to set a non-public field or invoke a private/protected setter method when testing the application code.

public class ReflectionUtilsTest {

    public void private_field_access() throws Exception {

        Secret myClass = new Secret();

        Field secretField = ReflectionUtils.findField(Secret.class, "secret", String.class); assertNotNull(secretField);

        assertEquals("zko", ReflectionUtils.getField(secretField, myClass));

        ReflectionUtils.setField(secretField, myClass, "cool");
        assertEquals("cool", ReflectionUtils.getField(secretField, myClass));


1. The component is really bad designed and had too many dependencies

If we need to re-mock many dependency beans, how about we extract the logic into an abstract class?

public abstract class MockedRepository {
    public ApplicationContext applicationContext;

    public NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public JdbcTemplate jdbc;

    public Security security;

    public UsersRepository usersRepository;

2. To mock it self

public class ItSelfRepositoryTest extends MockedRepository {

    private DependencyOne dependencyOne;

    private DependencyTwo dependencyTwo;

    private ItSelfRepository itSelfRepository;

    static class ItSelfRepositoryConfiguration {
        public ItSelfRepository itSelfRepository() {
            return new ItSelfRepository();

3. Override default Spring-Boot settings in Junit Test

You can use @TestPropertySource to override values in E.g.,

@SpringApplicationConfiguration(classes = ExampleApplication.class)
public class ExampleApplicationTests { }

NB. @TestPropertySource can accept a properties argument to overwrite some property inline, such as @TestPropertySource(properties = "myConf.myProp=valueInTest"), it’s useful in case that you don’t want a totally brand new property file.


Last update: Dec 2019