Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we’ll focus on how to mock final classes and methods using Mockito.

As with other articles focused on the Mockito framework (such as Mockito Verify, Mockito When/Then and Mockito’s Mock Methods), we’ll use the MyList class shown below as the collaborator in test cases.

We’ll add a new method for this tutorial:

public class MyList extends AbstractList<String> {
    final public int finalMethod() {
        return 0;
    }
}

And we’ll also extend it with a final subclass:

public final class FinalList extends MyList {

    @Override
    public int size() {
        return 1;
    }
}

2. Mock a Final Method

Once we’ve properly configured Mockito, we can mock a final method like any other:

@Test
public void whenMockFinalMethod_thenMockWorks() {

    MyList myList = new MyList();

    MyList mock = mock(MyList.class);
    when(mock.finalMethod()).thenReturn(1);

    assertThat(mock.finalMethod()).isNotZero();
}

By creating a concrete instance and a mock instance of MyList, we can compare the values returned by both versions of finalMethod() and verify that the mock is called.

3. Mock a Final Class

Mocking a final class is just as easy as mocking any other class:

@Test
public void whenMockFinalClass_thenMockWorks() {

    FinalList mock = mock(FinalList.class);
    when(mock.size()).thenReturn(2);

    assertThat(mock.size()).isNotEqualTo(1);
}

Similar to the test above, we create a concrete instance and a mock instance of our final class, mock a method and verify that the mocked instance behaves differently.

4. Conclusion

In this quick article, we covered how to mock final classes and methods with Mockito by using a Mockito extension.

The full examples, as always, can be found on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.