Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito 2 changes in any(Class) method

Tags:

java

mockito

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.

like image 905
Christian Avatar asked Feb 06 '23 13:02

Christian


1 Answers

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.

like image 61
Jeff Bowman Avatar answered Feb 08 '23 04:02

Jeff Bowman