I tried to solve it with reflection in @Before
annotated method, however, I didn't manage to get it working.
Solution you found out can be improved by creating your own static factory that creates mocks with an OptionalAnswer
and use it instead of default Mockito factory:
class MockitoOptional{
public static <T> T mock(Class<T> classToMock) {
return Mockito.mock(classToMock, new OptionalAnswer());
}
}
Next step will be to extend a test runner that will use this factory to inject mocks into @Mock
annotated fields. Search for custom JUnit test runners if you haven't heard of them yet.