Mockito matching primitive types

Martin Melka :

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.

Paul Boddington :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=469082&siteId=1