Mockito: inject class into physical interface

I am using Mockito 1.9.5 to run some unit tests. I am trying to insert a specific mock class into a class that has a private interface field. Here is an example:

Class i'm testing

@Component
public class Service {

    @Autowired 
    private iHelper helper;

    public void doSomething() {
        helper.helpMeOut();
    }
}

My test for this class

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private iHelper helper;

    @InjectMocks
    private Service service;

    @Before
    public void setup() {
        service = new Service();
    }

    @Test
    public void testStuff() {
        doNothing().when(helper).helpMeOut();
        service.doSomething();
    }
}

This code throws a NullPointerException when trying to call helper.helpMeOut () in doSomething (). I debugged and found that the helper was null when running the test. I also tried changing iHelper to a specific Helper class, and the same problem occurred.

Any suggestions? How can I get Mockito to correctly enter the layout in the personal field of the interface?

+4
source share
2 answers

@acdcjunior . Spring, ( ) . , . :

@Component
public class Service {

    @Autowired 
    private iHelper helper;

    public void doSomething() {
        helper.helpMeOut();
    }
}

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private iHelper helper;

    @InjectMocks
    @Autowired
    private Service service;

    @Test
    public void testStuff() {
        doNothing().when(helper).helpMeOut();
        service.doSomething();
    }
}

, - . !

+5

.

@Before
public void initMocks() {
    MockitoAnnotations.initMocks(this);
}

*

@InjectMock autowire

+2

All Articles