Mockito: Inject real objects into private @Autowired fields
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
Mockito-home
@Spy
@Mock
In Addition to @Dev Blanked answer, if you want to use an existing bean that was created by Spring the code can be modified to:
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Inject
private ApplicationContext ctx;
@Spy
private SomeService service;
@InjectMocks
private Demo demo;
@Before
public void setUp(){
service = ctx.getBean(SomeService.class);
}
/* ... */
}
This way you don't need to change your code (add another constructor) just to make the tests work.