Mockito Mock Final Classes and Methods Example

1. Introduction

Mocking final classes and methods can be challenging since they are not designed to be overridden. However, with Mockito 2.x and above, it is possible to mock final classes and methods by using a feature called "Mock the unmockable." Let's see how we can utilize this feature for our testing needs.

2. Example Steps

1. Define a final class with a final method.

2. Set up the Mockito environment to allow mocking of final classes/methods.

3. Mock the final class in a test class.

4. Stub and verify the behavior of the final method using Mockito.

5. Run the test.

3. Mockito Mock Final Classes and Methods Example

// Step 1: Define a final class with a final method
final class FinalClass {
    final String finalMethod() {
        return "Original Output";
    }
}

// Step 2 and 3: Set up Mockito to allow mocking of final classes/methods and mock the class
import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

public class FinalClassTest {

    @Test
    public void testFinalMethodMocking() {
        // Mock the FinalClass
        FinalClass mockedFinalClass = mock(FinalClass.class);

        // Stubbing the finalMethod to return a different value
        when(mockedFinalClass.finalMethod()).thenReturn("Mocked Output");

        // Calling the method on the mock and printing the result
        String result = mockedFinalClass.finalMethod();
        System.out.println(result);

        // Verifying the method's behavior
        verify(mockedFinalClass).finalMethod();
    }
}

Output:

Mocked Output

4. Step By Step Explanation

1. We first defined a FinalClass with a final method named finalMethod.

2. For Mockito to mock final classes and methods, the Mockito framework's internals are set up to handle this. Ensure you're using Mockito 2.x and above.

3. In the FinalClassTest, we mocked the FinalClass.

4. We then stubbed the behavior of the finalMethod using the when().thenReturn() approach, specifying that it should return "Mocked Output" instead of its original output.

5. When we called the finalMethod on the mocked object, it returned the stubbed value, "Mocked Output".

6. We then verified the behavior to ensure that our final method was indeed called. The output confirms that our mock was successful, demonstrating that Mockito can mock final classes and methods.


Comments