12

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.

Martin Melka
  • 7,177
  • 16
  • 79
  • 138
  • Please check my answer at https://stackoverflow.com/questions/21980728/mockito-for-int-primitive/53331588 using that you can verify any primitive type arguments – Ketan Nov 16 '18 at 04:47

2 Answers2

17

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

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116
7

The reason for the error is a little contrived - any() cannot be used in place of primitive data types.

anyChar(), anyDouble() etc. must be used instead for primitive types.

Martin Melka
  • 7,177
  • 16
  • 79
  • 138