Stubbing defaults in Mockito

1,146 views
Skip to first unread message

Alex

unread,
Nov 18, 2010, 10:32:02 AM11/18/10
to mockito
Hi,

How can I stub a method such that when given a value I'm not
expecting, it returns a default value? Looking at the documentation it
looks like you can change the default behaviour of all the methods on
a mock, but not those on a particular method. This seems like it would
be a pretty common requirement so I'm wondering if I'm missing
something.

Here's an example of what I'm looking to do:

Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenReturn("I don't know that string");

Also if possible, I'd like to be able to throw exceptions:

Map<String, String> map = mock(Map.class);
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");
when(map.get(anyString())).thenThrow(new
IllegalArgumentException("I don't know that string"));

Thanks,

Alex

Kristofer Karlsson

unread,
Nov 18, 2010, 10:47:08 AM11/18/10
to moc...@googlegroups.com
I haven't really verified this, but wouldn't it be enough to just reverse the order of the stubbing?



   Map<String, String> map = mock(Map.class);
   when(map.get(anyString())).thenReturn("I don't know that string");
   when(map.get("abcd")).thenReturn("defg");
   when(map.get("defg")).thenReturn("ghij");


--
You received this message because you are subscribed to the Google Groups "mockito" group.
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.


Alex

unread,
Nov 18, 2010, 10:52:21 AM11/18/10
to mockito
Yes.. that does work for the first example, but not in the thenThrow
example.

Map<String, String> map = mock(Map.class);
when(map.get(anyString())).thenThrow(new
IllegalArgumentException("I don't know that string"));
when(map.get("abcd")).thenReturn("defg");
when(map.get("defg")).thenReturn("ghij");

When creating the second stub, the IllegalArgumentException from the
anyString() stub is thrown.

Alex

On Nov 18, 3:47 pm, Kristofer Karlsson <kristofer.karls...@gmail.com>
wrote:
> > mockito+u...@googlegroups.com<mockito%2Bunsu...@googlegroups.com >
> > .

szczepiq

unread,
Nov 18, 2010, 11:22:03 AM11/18/10
to moc...@googlegroups.com
I this case, you have to use doReturn() syntax for stubbing. Sorry :)

Szczepan

To unsubscribe from this group, send email to mockito+u...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages