Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito matching primitive types

Tags:

java

mockito

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.

like image 627
Martin Melka Avatar asked Apr 02 '18 20:04

Martin Melka


1 Answers

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).

like image 64
Paul Boddington Avatar answered Sep 25 '22 00:09

Paul Boddington