I am getting an exception when setting up a mock using Mockito:
java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
The set up code is this:
Mockito
.when(aMock.method(any(), any()))
.thenReturn(something);
Where method
expects two double
arguments.
any()
returns null
. This choice was inevitable because the signature of any()
is
public static <T> T any()
Since generic types are erased in Java, and since nothing is passed to the method that carries any type information (such as a Class<T>
), null
is the only reasonable return value.
This creates a problem if the method of the mock has an argument of primitive type because unboxing this null
value throws a NullPointerException
.
There are two possible solutions. You can either use the primitive versions (such as anyDouble()
), or the version accepting a Class
(e.g. any(Double.class)
). In the latter case, since we are supplying type information to the method, it is possible to use this information to return a sensible non-null value (e.g. 0.0D
in the case of double).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With