How does Mockito handle overlapping matchers with multiple arguments in the thenReturn block

后端 未结 3 2677
醉梦人生
醉梦人生 2021-02-20 17:52

I\'ve got a block of test code that is attempting to, in the generic case return two values on subsequent calls, but in specific cases only return the value associated with that

3条回答
  •  無奈伤痛
    2021-02-20 18:39

    It's hard to say whether that's a bug or a feature... The thing is, when you call mockObject.method(eq("expectedInput1")) to perform the second stubbing, the first stubbing is already in place. So this call returns string1, which is then uselessly passed to when. Subsequent calls return string2, and that includes the call for the last stubbing and later calls during actual testing.

    I can hardly see any elegant way around it, short of using a custom Answer like @Nicolas suggested, although it does seem like an overkill. You could, perhaps, use a custom matcher instead of anyString(), that would essentially say “any string except those two”. This way you won't have one matcher intersect with another.

    P. S. Now that @Nicolas edited his answer, that regular expression looks like exactly what I meant. Except that you don't need to implement a custom matcher after all.

提交回复
热议问题