Default answer can be overridden by doReturn(..), but not when(..)
See original GitHub issueI just discovered that mocks with default Answer
s can not have their behavior overridden using stubbing with when(..)
, only with doReturn(..)
. The javadoc for Mockito.mock(Class, Answer) says that “It is the default answer so it will be used only when you don’t stub the method call.”, but this seems to only be the case if I stub method calls using doReturn
(or any doXyz
-method I suppose), but not when stubbing with when(..)
.
The following code demonstrates this:
abstract class MyInterface {
abstract byte[] getSomeData();
}
MyInterface mock = mock(MyInterface.class, i -> {
throw new UnsupportedOperationException("method: " + i.getMethod());
});
when(mock.getSomeData()).thenReturn(new byte[0]);
//doReturn(new byte[0]).when(mock).getSomeData();
mock.getSomeData();
(Can be pasted into any test method. I used an abstract class to have the code self-contained for a method scope, but the behavior is the same for an interface.)
The invocation of mock.getSomeData()
will invoke the default answer and throw the UnsupportedOperationException
. If you comment out the when
-stubbing, and uncomment the doReturn
-stubbing, the mock.getSomeData()
yields the expected stubbed return value.
I have tested this with v2.10.0 and v2.18.3, and I observe the same behavior.
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
Not an embarrassment at all! We have had multiple of these reports and we are looking for alternatives to resolve this situation. Good luck mocking 😃
Being able to set te default answer after stubbing could be a solution, what do you think?