1

Is there an easy way to have Mockito throw an exception when a mocked class's un-stubbed method is called instead of returning a default value (null, false, 0, etc)?

Inevitably there's a (typically more cryptic) NullPointerException thrown down stream but that can be hard to trace back to the unstubbed method.

The docs say it always returns a default value unless stubbed: https://javadoc.io/static/org.mockito/mockito-core/3.3.1/org/mockito/Mockito.html#stubbing

I looked at the MockSettings and didn't see any way to change the behavior: https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/MockSettings.html

There's a similar question but there aren't any easy solutions, only workarounds proposed. Throw a RuntimeException when invoking an unstubbed method

Charlie
  • 8,530
  • 2
  • 55
  • 53
  • Apparently you can configure a default answer for unstubbed invocations - see https://javadoc.io/static/org.mockito/mockito-core/2.2.0/org/mockito/configuration/DefaultMockitoConfiguration.html – hoipolloi Mar 10 '20 at 22:16
  • @rdas I glanced at that when I looked earlier and disregarded it as not the same question but after reading it more carefully, it's quite similar. The answers there, including the accepted answer, are more workarounds than solutions. – Charlie Mar 10 '20 at 22:42

0 Answers0