Mocking final method with Mockito framework

December 26, 2020 No comments Mockito Java final mock

1. Introduction

In this article, we will show a way to mock the final method with Mockito testing framework. Fortunately, from version 2 Mockito supports final classes and methods.

2. Mocking final method using mockito-inline

The following dependency need to be added into your project in order to start mocking final/static methods in unit tests:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>3.6.28</version>
    <scope>test</scope>
</dependency>

The latest version of this library could be found here.

When you try to mock final/static classes with an older version of Mockito or without configuring mockito-inline dependency you will face the error like this:

Mockito cannot mock/spy because :
 - final class

The best way to explain how mocking final methods works is to present a simple piece of code with an example.

Let's consider we have a final class with a final method that returns a welcome message:

package com.frontbackend.libraries.mockito;

public final class FinalWelcomeUtil {

    public final String getWelcomeMessage(String name) {
        return String.format("Welcome %s", name);
    }
}

The unit test that makes use of Mockito to mock this final class could have the following structure:

package com.frontbackend.libraries.mockito;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

import org.junit.Test;

public class MockitoFinalMethodTest {

    @Test
    public void testMockingFinalMethod() {
        FinalWelcomeUtil finalClass = new FinalWelcomeUtil();

        FinalWelcomeUtil mock = mock(FinalWelcomeUtil.class);
        given(mock.getWelcomeMessage("John")).willReturn("not anymore");

        assertNotEquals(mock.getWelcomeMessage("John"), finalClass.getWelcomeMessage("John"));
        assertEquals("not anymore", mock.getWelcomeMessage("John"));
        assertEquals("Welcome John", finalClass.getWelcomeMessage("John"));
    }
}

In this code first, we initialize FinalWelcomeUtil to check if the 'untouched' class will behavior as implemented. Then we create a mock and configure the final getWelcomeMessage method to return always static text regardless of input parameters.

The following assertions confirm that mocking final method works:

assertEquals("not anymore", mock.getWelcomeMessage("John"));
assertEquals("Welcome John", finalClass.getWelcomeMessage("John"));

3. Conclusion

This article presented an easy way to mock the final method with the Mockito framework. Note that mocking this kind of method is not recommended and need to be explicitly activated to be available.

As usual the code used as an example in this article is available under our GitHub repository.

{{ message }}

{{ 'Comments are closed.' | trans }}