Search code examples
javajunitnullpointerexceptionprivatepowermock

NullPointerException while injecting mock in PowerMock


I am trying to mock private method inside singleton bean. Test class looks like:

import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.when;

import java.util.Hashtable;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(SampleBean.class)
public class SampleBeanTest{
    @InjectMocks
    private SampleBean sampleBean = new SampleBean();


    /**
     * Sets the up.
     * @throws Exception the exception
     */
    @Before
    public final void setUp() throws Exception {
        //MockitoAnnotations.initMocks(SampleBean);
        PowerMockito.doReturn("response").when(sampleBean, "privateMethod", anyObject(), DUMMY_QUEUE);
    }

    @Test
    public void testGetData() throws Exception {
        sampleBean.publicMethod();

    }
}

When I run test, I get exception as:

java.lang.NullPointerException: null
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:68)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.prepareForStubbing(PowerMockitoStubberImpl.java:123)
    at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:91)
    at com.temp.SampleBeanTest.setUp(SampleBeanTest.java:30)

I found out that PowerMock returns null at line:

MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock);

I am not sure what is the reason behind this weird behavior. Please let me know, if you have any idea.


Solution

  • It looks like sampleBean is null.

    You need the MockitoAnnotations.initMocks call that is commented-out, but like this:

    MockitoAnnotations.initMocks(this);
    

    Or, doing it manually:

    sampleBean = mock(SampleBean.class);