我正在使用PowerMockRunner测试一个类,它从一个助手类的静态方法中检索一个value枚举。将此value枚举传递到classUnderTest中的SWITCH语句中时,将抛出空指针。
我已经调试过了,可以看到ENUM设置正确(名称、类型、序号都是预期的),所以我不确定为什么会抛出NPE。有谁遇到过类似的问题吗?
注意:由于classUnderTest包含对私有方法的调用,因此PowerMockito是必需的。下面是删除了大量代码(与问题无关)的完整示例。在设置ENUM并抛出NPE时添加的注释
ClassUnderTest:
public class TestService extends BaseXAServiceBean
{
@Override
public ValueObject runExecute(ValueObject param) throws RemoteException, ServiceException
{
try
{
ValueEnum value = ValueServiceHelper.getValueType(param1(),
param2());
// value populated successfully with ENUM at this point
// NPE thrown when value is passed into below switch
switch (value)
{
case VALUE1:
{
// logic here...
break;
}
case VALUE2:
{
// logic here...
break;
}
case VALUE3:
{
// logic here...
break;
}
}
}
catch (ServiceException e)
{
throw e;
}
catch (Exception e)
{
throw new ServiceException(e, AppErrorCodes.INT.SL06, AppErrorCodes.SL06.E04);
} finally {
// clean up
}
}
}具有静态方法的Helper类:
public class ValueServiceHelper
{
public static ValueEnum getValueType(String param1, String param2) throws ServiceException
{
ValueEnum retVal = ValueEnum.VALUE3;
// proxy is mocked
ProductProxy proxy = ProxyFactory.createFactory("1").getProductProxy();
try
{
if (proxy.isValue1(param2))
{
retVal = ValueEnum.VALUE1;
}
else if (proxy.isValue2(param2))
{
retVal = ValueEnum.VALUE2;
}
}
return retVal;
}
}测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ProxyFactory.class})
public class ValueTest {
@Spy
@InjectMocks
private TestService service = new TestService();
@Mock
private ProxyFactory proxyFactory;
@Mock
private Proxy proxy;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(ProxyFactory.class);
}
@Test
public void testSuccess() throws Exception {
// given
// when
PowerMockito.when(ProxyFactory.createFactory("1")).thenReturn(proxyFactory);
PowerMockito.when(proxyFactory.getProductProxy()).thenReturn(proxy);
PowerMockito.when(proxy.isValue1(param2)).thenReturn(true);
PowerMockito.when(proxy.isValue2(param2)).thenReturn(true);
service.runExecute(request);
// then
}
}发布于 2017-08-30 21:39:48
这是已经存在的since at least 2015的PowerMock的问题。据我所知,修复它的唯一方法是使用if语句而不是switch。
https://stackoverflow.com/questions/45941180
复制相似问题