MockitoAnnotations.openMocks(this) method has to be called to
initialize annotated objects.
See Annotation Type Mock.
So the test class should look like the following:
public class SomeClassTest {
@Mock
A a;
@InjectMocks
SomeClass someClass;
private AutoCloseable closeable;
@BeforeEach
public void openMocks() {
closeable = MockitoAnnotations.openMocks(this);
}
@AfterEach
public void releaseMocks() throws Exception {
closeable.close();
}
@Test
void test() {
Mockito.when( a.foo() ).thenReturn(true);
Assertions.assertDoesNotThrow( () -> someClass.doSomeThing() );
}
}
Edit
After receiving two downvotes on the answer, I took a second look at the question and recognized, that my code did solve an Exception issue but still did not anwer the question.
If we add the following annotation to the test class, the test will indeed fail with an Exception:
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
The error message is: "Unnecessary stubbings detected."
So my code did create a Mock a as member of SomeClassTest
but it did not replace the local variable a in SomeClass.doSomeThing
. The anotation InjectMocks
has no means to replace that local variable by a Mock. As stated in the documentation:
Mockito will try to inject mocks only either by constructor injection, setter injection, or property injection
So the only way to mock local Variable a in SomeClass.doSomeThing
is by also mocking local Variable b and returning the member a of SomeClassTest. And as b can not be injected along the same arguments as for a, you need to refactor your code in a way, that a and b can get mocked. (As knittl already provided this solution, i will not repeat it.)