Reputation: 23052
When there's some object with a boxed type property, the getter of the property returns 0
. But this should return null
, because the default value of the boxed type property is null
. What is the problem here?
class Person {
private Long id;
public Long getId() {
return id;
}
}
...
@Mock Person person;
...
person.getId(); // 0 instead of null
Upvotes: 17
Views: 5353
Reputation: 42273
That's simply the chosen default value for primitive and wrapper types in the default Mockito answer.
This 0
default has been chosen when null
was used and too many users experienced NPEs due to unboxin, hard to diagnose for novices in particular, when null
was used.
While this might be surprising for people used to reference and un/boxing, this trade-off was worth it in usability.
One day maybe this could be revisited when/if Java gets a nullability notation reachable via reflection.
And regardless mockito allows you to change the default answers if it doesn't suit the project/team.
Upvotes: 15
Reputation: 1847
I had the same problem and my solution was to change the default answer of the mock to null
:
Person person;
...
person = mock(Person.class, new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
return null;
}
});
person.getId(); // null!
(Not sure if the default answer can be set if you want to use the @Mock
annotation)
If for some reason you would only like to set the default for Long
(and not for example Integer
) this should do the trick inside the answer
method:
if(invocation.getMethod().getReturnType().equals(Long.class)){
return null;
}else{
return Mockito.RETURNS_DEFAULTS.answer(invocation);
}
Upvotes: 4
Reputation: 531
That is the correct value that is getting returned for the getter method.
When you Mock a class in Mokito all the methods in the class also get mocked. so inherintely this does not matter with the boxed type property being set to Null. As you see its LONG value that you have as a instance variable whose default value is 0L.
So person.getId() will always return 0 and not NULL.
Upvotes: -1