我正在使用PowerMockRunner测试一个类,它从辅助类中的静态方法中检索value
ENUM。将value
ENUM传递给classUnderTest中的SWITCH语句时,抛出空指针。
我已经调试过,可以看到ENUM设置正确(名称,类型,序号都按预期),所以我不确定为什么会抛出NPE。有人遇到过类似的问题吗?
注意:PowerMockito是必需的,因为classUnderTest包含对私有方法的调用。下面是完整的示例,其中删除了大量代码(与问题无关)。在设置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
}
}
}
使用静态方法的助手类:
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
}
}