I wanted to post this as a separate answer since this should better address your actual question regarding @Mock, @Autowired and @InjectMocks.
@Mock
: This marks a field that should be created as a mock (using mock(MyClass.class)
) when MockitoAnnotations.initMocks(this)
is called.
@Autowired
: Marks a field that should be assigned by Spring with a bean that implements the class / interface.
@InjectMocks
: Marks a field that should be CREATED by Mockito when MockitoAnnoations.initMocks(this)
is called. It creates an instance of the class and injects the @Mock
-annotated fields into this instance. (see correction to this statement in comments).
Analysis:
@InjectMocks
is not compatible with Spring contexts and @Autowired
because InjectMock
creates a new instance of the class it does not use the Spring instance.
To do what you are looking for, you need to use Springockito. (delayed update) Springockito will allow you to inject mocks into your Spring context and thereby have those mocks used as Autowired
candidates. It allows for Mocks and Spys. Using ReplaceWithMock
and Autowired
on the same field in your test is the general practice (as is shown in the example on the wiki).