I've updated to Mockito 2.1 from version 1.9.
Now some of my tests fail. There seems to be a change in the any(Bla.class)
method. Before this test was fine:
when(criteriaBuilder.greaterThanOrEqualTo(any(Expression.class),
any(Comparable.class)))
.thenReturn(predicate);
Now the expression any(Expression.class)
is null.
Do I need to use another method to make it work again?
I got it working with (Expression)any()
but that doesnt look right to me.
Drop the Expression.class
and call any
without parameters:
when(criteriaBuilder.greaterThanOrEqualTo(any(), any()))
.thenReturn(predicate);
As of Mockito 2, any(T.class)
changed meaning: Where before it meant "any reference including null, cast to the type T
to avoid an explicit cast in Java 7 and previous", it changed to read "any instance of class T
": Thus, any(Foo.class)
would stop matching null
during an upgrade from 1.x to 2.x.
any()
without parameters still means "any reference including null", consistent across 1.x to 2.x, so calling (Expression) any()
or ArgumentMatchers.<Expression>any()
can restore the behavior you want. Because of the improved generic type inference rules in Java 8, you may also be able to call any()
and have Java infer the type.
Don't worry about expressions like any
returning null
, by the way: That's how Mockito matchers work. A separate stack tracks "how to match this argument", rather than returning a "special instance" or "special value"; this is necessary because Java is strongly-typed enough that there's no way to encode the idea "greater than 5" within the int
that gt(5)
returns. 0
and null
are safe default values, so Mockito returns them while storing the concept of any
or gt(5)
in the corresponding position on the stack.
The NullPointerException is probably coming from your code receiving null
(the default value for stubbed calls) where it was expecting to receive predicate
.
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