2

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.

4
  • 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. Commented Sep 23, 2021 at 21:58
  • Make sure your call to QueryUtils.toOrder in the code has the same types you've passed on the test code. Commented Sep 23, 2021 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. Commented Sep 23, 2021 at 23:09
  • Does this answer your question? Mockito - NullpointerException when stubbing Method Commented Jul 7, 2022 at 7:59

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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().
My stubbing -> when(mock.mehtod(any(), any())).thenReturn(obj) I was also getting a NPE when using both @RunWith(MockitoJUnitRunner.class) and @ExtendWith(MockitoExtension.class) class annotations. I changed the class to just be annotated with @RunWith(MockitoJUnitRunner.class). I then got a InvalidUseOfMatchersException. After that I changed my stubbing to when(mock.mehtod(anyString(), anyInt())).thenReturn(obj). The any() matcher here is not appropriate for a primitive int.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.