You have two options: Matching "any value but one", and overriding stubbing. (I suppose you could also use an Answer for complex custom behavior, but that's overkill for situations like this one.)
Stubbing any value except a given value
Mockito's AdditionalMatchers
class offers a number of useful matchers, including operators such as not
. This would allow you to set behavior for all values except for a specific value (or expression).
when(foo.bar(1)).thenReturn(99);
when(foo.bar(not(eq(1)))).thenThrow(new IllegalArgumentException());
Be careful to note that operators must be used with matchers instead of values, possibly requiring Matchers.eq
as an explicit equals
matcher, due to Mockito's argument matcher stack:
/* BAD */ when(foo.bar(not( 1 ))).thenThrow(new IllegalArgumentException());
/* GOOD */ when(foo.bar(not(eq(1)))).thenThrow(new IllegalArgumentException());
Overriding stubbing
For stubbing, the last-defined matching chain wins. This allows you to set up general test fixture behavior in a @Before
method and override it in individual test cases if you wish, but also implies that order matters in your stubbing calls.
when(foo.baz(anyInt())).thenReturn("A", "B"); /* or .thenReturn("A").thenReturn("B"); */
when(foo.baz(9)).thenReturn("X", "Y");
foo.baz(6); /* "A" because anyInt() is the last-defined chain */
foo.baz(7); /* "B" as the next return value of the first chain */
foo.baz(8); /* "B" as Mockito repeats the final chain action forever */
foo.baz(9); /* "X" because the second chain matches for the value 9 */
foo.baz(9); /* "Y" forever because the second chain action still matches */
Consequently, you should never see the two stubs in the order listed in the question, because if a general match immediately follows a specific match then the specific match will never be used (and may as well be deleted).
Beware that you'll sometimes need to change syntax to doAnswer
when overriding spies or dangerous stubbed behavior. Mockito knows not to count calls to when
for verification or for advancing along thenVerb
chains, but exceptions could still cause your test to fail.
/* BAD: the call to foo.bar(1) will throw before Mockito has a chance to stub it! */
when(foo.bar(anyInt())).thenThrow(new IllegalArgumentException());
when(foo.bar(1)).thenReturn(99);
/* GOOD: Mockito has a chance to deactivate behavior during stubbing. */
when(foo.bar(anyInt())).thenThrow(new IllegalArgumentException());
doReturn(99).when(foo).bar(1);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…