Stubbing defaults in Mockito

Alex Spurling picture Alex Spurling · Nov 18, 2010 · Viewed 15.3k times · Source

How can I stub a method such that when given a value I'm not expecting, it returns a default value?

For example:

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");

Part 2: As above but throws an exception:

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"));

In the above examples, the last stub takes precedence so the map will always return the default.

Answer

Alex Spurling picture Alex Spurling · Nov 20, 2010

The best solution I have found is to reverse the order of the stubs:

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");

When the default is to throw an exception you can just use doThrow and doReturn

doThrow(new RuntimeException()).when(map).get(anyString());
doReturn("defg").when(map).get("abcd");
doReturn("ghij").when(map).get("defg");

https://static.javadoc.io/org.mockito/mockito-core/2.18.3/org/mockito/Mockito.html#12