Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can mock() be used to mock final classes or methods


Can mock() be used to mock final classes or methods


Yes, Mockito can be used to mock final classes or methods, but with some limitations.

In earlier versions of Mockito, mocking final classes or methods was not possible. However, starting from Mockito 2.1.0, the framework introduced the ability to mock final classes and methods, but with some caveats.

Here's how you can use `mock()` to mock final classes or methods:

1. Mocking Final Classes:
Mockito can now mock final classes, but you need to use the `MockSettings` class to enable this functionality.

java
   MyFinalClass mockedFinalClass = Mockito.mock(MyFinalClass.class, Mockito.withSettings().finalizable());
   

The `withSettings().finalizable()` method tells Mockito to create a mock that can handle final classes.

2. Mocking Final Methods:
Mocking final methods is also possible, but you need to use the `Mockito.spy()` method instead of `Mockito.mock()`.

java
   MyClass spiedClass = Mockito.spy(MyClass.class);
   when(spiedClass.myFinalMethod()).thenReturn("mocked value");
   

By using `Mockito.spy()`, you can create a partial mock that allows you to override the behavior of final methods.

It's important to note that while Mockito can mock final classes and methods, there are still some limitations:

- Mocking private methods is not possible, as they are not accessible from the test code.
- Mocking static methods is also not possible with the standard Mockito API. You would need to use additional libraries like PowerMock or Mockito-Inline to achieve this.

Additionally, mocking final classes or methods can make your tests more fragile and less maintainable, as the implementation details of the class or method being mocked are tightly coupled to the test. It's generally recommended to use mocking sparingly and focus on testing the public API of your classes.

In summary, Mockito can be used to mock final classes and methods, but you should be cautious about the potential drawbacks and consider alternative testing approaches, such as using interfaces or partial mocks, whenever possible.

Citations:
[1] https://intellipaat.com/blog/tutorial/mockito-tutorial/methods-of-mockito/
[2] https://www.vogella.com/tutorials/Mockito/article.html
[3] https://ioflood.com/blog/mockito-verify/
[4] https://www.javatpoint.com/methods-of-mockito
[5] https://semaphoreci.com/community/tutorials/stubbing-and-mocking-with-mockito-2-and-junit