Why does a mockito mock return 0 when it should return null?

When there is an object with a property of type boxed, the getter of the property returns 0 . But this should return null , because the default value for the boxed type property is null . What is the problem?

 class Person { private Long id; public Long getId() { return id; } } ... @Mock Person person; ... person.getId(); // 0 instead of null 
+8
java unit-testing mockito mocking
source share
3 answers

This is just the default selected for primitive and wrapper types in the default Mockito answer.

+5
source share

I had the same problem and my solution was to change the standard layout response 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 you can set a default answer if you want to use @Mock annotation)

If for some reason you would like to set the default value 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); } 
+2
source share

This is the correct value returned for the getter method.

When you mock a class in Mokito, all methods in the class are also mocked. so inheritance doesn’t matter if the boxed type property is set to Null. Since you see its LONG value, which you have as an instance variable, whose default value is 0L.

So person.getId () will always return 0, not NULL.

0
source share

All Articles