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 FreeUnit 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:
interface Animal {
String getName();
}
xxxxxxxxxx
class Dog implements Animal {
String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
x
public final class AnimalUtils {
private AnimalUtils() {}
public static Dog getGermanShepherd() {
return new Dog("german shepherd");
}
public static Dog getKangal() {
return new Dog("kangal");
}
public static Animal getAnimal() {
return getGermanShepherd();
}
}
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:
xxxxxxxxxx
void animalUtilsTest() {
Animal kangal = AnimalUtils.getKangal();
try (MockedStatic<AnimalUtils> fooUtilsMocked = Mockito.mockStatic(AnimalUtils.class, invocation -> {
Method method = invocation.getMethod();
if ("getAnimal".equals(method.getName())) {
return invocation.callRealMethod();
} else {
return invocation.getMock();
}
})) {
fooUtilsMocked.when(AnimalUtils::getGermanShepherd).thenReturn(kangal);
Animal animal = AnimalUtils.getAnimal();
assertThat(animal.getName()).isEqualTo("kangal");
}
}
Opinions expressed by DZone contributors are their own.
Comments