1

I am trying to stub this method: QueryUtils.toOrder(sort, root, builder) and I am doing

when(QueryUtils.toOrder(any(Sort.class), any(Root.class), any(CriteriaBuilder.class)).thenReturn(mock(List.class));

but it goes into the queryUtils method body and it will say Sort is null and it will throw a NPE. But why would it need to go into the method body when it is a stub? I haven't had this issue before and I don't think it should care what the internal logic of the method is.

  • You may have more things in your classes than your database, which will make them null, or you may have some nullable things in your query but these are not nullable in your class, which will give you error. – Sahin Sep 23 '21 at 21:58
  • Make sure your call to QueryUtils.toOrder in the code has the same types you've passed on the test code. – Renan Felipe Ferreira Sep 23 '21 at 22:08
  • @RenanFelipeFerreira It fails when it is setting the when(...).thenreturn() in the test in the arrange phase. It gets a null pointer exception, not when acting. – stackunderflow123 Sep 23 '21 at 23:09
  • Does this answer your question? [Mockito - NullpointerException when stubbing Method](https://stackoverflow.com/questions/33124153/mockito-nullpointerexception-when-stubbing-method) – Étienne Miret Jul 07 '22 at 07:59

1 Answers1

2

The Problem here is that Mockito cannot brake the Java language.

In the when(mockedObject.mockedMethod()).thenReturn() form the mocked method is executed and its return value is passed into the mock where Mockito exchanges it with the configured value. But the mocked object is initialized with nulls so any property of the mocked object that is accessed in the mocked method raises a NPE.

To come around you should use the slidely less readable form doReturn().when(mockObject).mockedMethod().
please notice the closing ) moved!
In this form Mockito prevents the execution of the mocked method by polymorphism entirely and directly returns the configured value.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • With the `when(mock.method())` form, the **mock method** is ran, but not the **mocked method**. The mock method itself is (mostly) a noop and wont throw any exception, unless configured to do so with `when(mock.method()).thenThrow()`. – Étienne Miret Jul 07 '22 at 07:58