在PowerMock中注入mock时出现NullPointerException

时间:2016-03-16 09:49:35

标签: java junit nullpointerexception private powermock

我正在尝试在singleton bean中模拟私有方法。测试类看起来像:

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();

    }
}

当我运行测试时,我得到例外:

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)

我发现PowerMock在第<:p>行返回null

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

我不确定这种奇怪行为背后的原因是什么。如果您有任何想法,请告诉我。

1 个答案:

答案 0 :(得分:2)

看起来sampleBean为空。

您需要注释掉的MockitoAnnotations.initMocks来电,但是这样:

MockitoAnnotations.initMocks(this);

或者,手动完成:

sampleBean = mock(SampleBean.class);