4

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.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60
Christian
  • 22,585
  • 9
  • 80
  • 106
  • Please confirm that `criteriaBuilder` is a mocked object? Why would you care if `any()` returns a null value? It shouldn't be used in calling your implementation code anywhere, unless I've misinterpretted your question. – Brad Dec 09 '16 at 13:51
  • FYI there is some [changes in v2](https://github.com/mockito/mockito/wiki/What's-new-in-mockito-2) around the use if `any()` but I'm not sure it would affect the problem you are describing – Brad Dec 09 '16 at 13:53

1 Answers1

8

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.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251