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:
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:
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:
The unit test that makes use of Mockito to mock this final class could have the following structure:
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:
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.
{{ 'Comments (%count%)' | trans {count:count} }}
{{ 'Comments are closed.' | trans }}