I'm using Mockito's @Mock
and @InjectMocks
annotations to inject dependencies into private fields which are annotated with Spring's @Autowired
:
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Mock
private SomeService service;
@InjectMocks
private Demo demo;
/* ... */
}
and
public class Demo {
@Autowired
private SomeService service;
/* ... */
}
Now I would like to also inject real objects into private @Autowired
fields (without setters). Is this possible or is the mechanism limited to injecting Mocks only?
Use @Spy
annotation
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Spy
private SomeService service = new RealServiceImpl();
@InjectMocks
private Demo demo;
/* ... */
}
Mockito will consider all fields having @Mock
or @Spy
annotation as potential candidates to be injected into the instance annotated with @InjectMocks
annotation. In the above case 'RealServiceImpl'
instance will get injected into the 'demo'
For more details refer