gpt4 book ai didi

java - 在 PowerMock 中注入(inject)模拟时出现 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 08:39:41 25 4
gpt4 key购买 nike

我正在尝试模拟单例 bean 中的私有(private)方法。测试类看起来像:

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

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

最佳答案

看起来 sampleBean 是空的。

您需要被注释掉的 MockitoAnnotations.initMocks 调用,但像这样:

MockitoAnnotations.initMocks(this);

或者,手动执行:

sampleBean = mock(SampleBean.class);

关于java - 在 PowerMock 中注入(inject)模拟时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36032040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com