How to mock static methods using Mockito
Mockito is long used for mocking interfaces and providing stubs for unit testing with Junit. However, the functionality of testing static methods was missing until Mockito version 3.4.x. Traditionally, Powermock is used to mock static methods. This makes the static methods easy to test but additional libraries are required. In this article, I provide a brief description of how to use Mockito version 3.4.x to test the static methods.
Dependencies
The project is Java Gradle based, which means all dependencies are included in built.gradle file. Similar dependencies can also be imported into the maven project. For the POM, see the corresponding Maven central repository.
To run the static mocking, we need ‘mockito-core’, and ‘mockito-inline’. Byte-buddy is not necessary if your project already includes byte-buddy version 1.10.13, otherwise include the dependencies since Mockito version 3.4.0 work with a specific version.
Fictional Calculator
In this article, we will test a factional ‘Calculator’, its ‘calculate’ method takes string expression as input and use the static methods ‘add’, and ‘multiply’ from ‘MathUtitls’ to do the actual calculation. Imagine, the operations (add, multiply) can’t be used directly and need extra configurations or network access (currently it throws exceptions) in the testing, therefore these methods must be mocked to test the ‘calculate’ method.
Testing and Mocking
To mock the static methods, we have to create a mock controller, which remain active for the current thread. This mock controller is then further used in stubbing methods, instead of using the actual class. It is better to define the mock controller in the @BeforeClass or @BeforeAll method.
After defining the mock controller, we can then define the stubbing methods, these methods can be inside the @Before method if you want to run it for each method or inside a specific test method. The mock controller shall be used instead of the actual class.
After defining the stubbing methods, one can then write the actual tests, where the internal static methods will now return the mock value rather than the actual value.
The final step is to close the mock controller, it should be closed in the @AfterClass or @AfterAll method.
Conclusion
In this brief article, I explained how can one use Mockito to mock static methods of a fictional calculator without using Powermock. In the future, I will write more articles about new features supported by Mockito.
References & Source-Code
Full source code is publically accessible from my Github repository. Further links for used libraries and documentation are also given below.