Unit Testing Static Methods With Mockito
Unit testing can be hard especially when you need to test a method that is static, this tutorial will help you to easily mock static methods.
Join the DZone community and get the full member experience.Join For Free
Unit testing helps us to cover different scenarios and it is a way to ensure the applications behave as expected under certain circumstances. Most of the time it is easy to test your classes and methods, but sometimes you need to mock certain services or methods to isolate your target. Mockito is a good library to help you with that. It can easily create mocked or partially mocked objects for you with Mockito#mock or with Mockito#spy.
There are some cases that we also want to mock static methods of a particular utility class, so how can we accomplish that? Well by using the Mockito mockStatic method. Lets take an example by using the following AnimalUtils, Dog objects and Animal Interface:
The above AnimalUtils getAnimal method always invokes the getGermanShepherd method, but in a real use case scenario this could be a call to a service or to be more specific a database call or something else. We will mock the static method getGermanShepherd and preserve the behavior of the getAnimal method. In this way, we can isolate the getAnimal method and validate if that method is calling getGermanShepherd. See below for the unit test:
Opinions expressed by DZone contributors are their own.