returns 0 instead of null for an Integer

1,822 views
Skip to first unread message

Tim Van Laer

unread,
Feb 22, 2012, 6:08:05 AM2/22/12
to moc...@googlegroups.com
While writing some JUnit tests, I found the following in the documentation:

Default return values for primitive wrapper classes are now consistent with primitives. E.g: an int method returns 0 but an Integer method also return 0 instead of null.

Is there a way to turn this off? I would like to let Mockito return "null" for an Integer, instead of the primitive value. Is it possible without stubbing the particular method(s)?

The class:

public class MyClass{
    private Integer id;

    public Integer getId(){
        return this.id;
    }
}

In the JUnit test:

MyClass mock = mock(MyClass.class);

if(mock.getId() != null){
   // do something  never gets here because mock.getId() return 0
}

Szczepan Faber

unread,
Feb 22, 2012, 6:51:14 AM2/22/12
to moc...@googlegroups.com
In my opinion you should avoid writing tests that depend on the Mockito's default return values. If returning null is an important part of the behavior that the test describes then it should be declared explicitly, i.e:

MyClass mock = mock(MyClass.class);
when(mock.getId()).thenReturn(null);
//or a one-liner (only if it makes sense!):
MyClass oneLiner = when(mock(MyClass.class).getId()).thenReturn(null).getMock();

You can change the default return values either on mock creation via MockSettings or globally via MockitoConfiguration. However, I think this is not the way to go in your use case.

If the returning null is important -> make that explicit in the test.

Hope that helps!


--
You received this message because you are subscribed to the Google Groups "mockito" group.
To view this discussion on the web visit https://groups.google.com/d/msg/mockito/-/7TtiCMEFYKIJ.
To post to this group, send email to moc...@googlegroups.com.
To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/mockito?hl=en.



--
Szczepan Faber
Principal engineer@gradleware
Lead@mockito

Tim Van Laer

unread,
Feb 22, 2012, 8:25:12 AM2/22/12
to moc...@googlegroups.com
Hi Szczepan,

Thanks for the explanation. Now that we understand the behaviour of the default return values, we will explicitly stub the particular methods (instead of changing the MockSettings)

Best regards,
Tim
Reply all
Reply to author
Forward
0 new messages