【发布时间】:2016-03-16 09:49:35
【问题描述】:
我正在尝试在单例 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 在以下行返回 null:
MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock);
我不确定这种奇怪行为背后的原因是什么。如果您有任何想法,请告诉我。
【问题讨论】:
标签: java junit nullpointerexception private powermock