Mockito: Inject real objects into private @Autowired fields

user2286693 picture user2286693 · Nov 28, 2013 · Viewed 114.6k times · Source

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?

Answer

Dev Blanked picture Dev Blanked · Nov 28, 2013

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