zongweil
zongweil

Reputation: 2051

Mockito: inject a class mock into a private interface field

I'm using Mockito 1.9.5 to do some unit testing. I'm trying to inject a concrete class mock into a class that has a private interface field. Here's 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 helper was null when running the test. I also tried changing iHelper to the concrete class Helper, and the same issue happened.

Any suggestions? How can I get Mockito to correctly inject a mock into an interface private field?

Upvotes: 5

Views: 15426

Answers (2)

zongweil
zongweil

Reputation: 2051

@acdcjunior's comment helped me figure out the issue. Instantiating service using the new keyword caused Spring to not inject the dependencies (in this case helper) correctly. I fixed this by autowiring in service in the test. My final working code looks like this:

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
    @Autowired
    private Service service;

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

Hope this helps someone else. Thanks for the suggestions!

Upvotes: 5

Alexander Campos
Alexander Campos

Reputation: 111

According to the docs you are missing the setup.

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

Edited*

Take at look at this page why you should not use @InjectMock to autowire fields

Upvotes: 2

Related Questions