Since Java 8 you can use the argument-less any
method and the type argument will get inferred by the compiler:
verify(bar).doStuff(any());
The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).
In this case the parameter type of doStuff
will be the target type for any()
, and the return value type of any()
will get chosen to match that argument type.
This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.
This doesn't work with primitive types, unfortunately:
public interface IBar {
void doPrimitiveStuff(int i);
}
verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead
The problem is that the compiler will infer Integer
as the return value type of any()
. Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null
. The runtime will try to unbox the return value by calling the intValue
method on it before passing it to doStuff
, and the exception gets thrown.