I'd like to use strict mocks, at least when developing for the first time some tests against old code, so any methods invoked on my mock will throw an exception if I didn't specifically define expectations.
From what I've come to see, Mockito if I didn't define any expectations will just return null, which will later on cause a NullPointerException in some other place.
Is it possible to do that? If yes, how?
Add this
@Rule
to your test class as a public field:This value was added to Mockito in version 2.3.0
From the documentation:
Bellow Methods can verify no unexpected method called:
You could use
verifyNoMoreInteractions
. It's useful if the tested class catches exceptions.Result:
What do you want it to do?
You can set it to RETURN_SMART_NULLS, which avoids the NPE and includes some useful info.
You could replace this with a custom implementation, for example, that throws an exception from its
answer
method:In addition to the
MockitoRule
approach, if you don't need to use a specific test runner (and you are using Mockito 2.5.1 or higher), you could also consider using theMockitoJUnitRunner.StrictStubs
runner, i.e.(I would have commented on the post about MockitoRule, but don't have that ability yet)
According to the source code of org.mockito.Mockito.RETURNS_DEFAULTS it selects its "what to do if no expectation" from a global setting. Furthermore "If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)" I have not yet been able to make that configuration.