0

我正在用PowerMockRunner測試一個類,它從輔助類的靜態方法中檢索value ENUM。將此枚舉傳遞給classUnderTest中的SWITCH語句時,會拋出空指針。PowerMockito枚舉在Switch語句拋出NPE

我已經調試,可以看到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 

} 
} 
+1

您需要提供完整的可驗證示例。這裏沒有足夠的信息來回答。 –

+0

現在更新,包括完整的例子.... –

+1

[也許有關?](https://github.com/powermock/powermock/issues/394)看看是否使用'if'語句解決了這個問題。 –

回答

1

這是PowerMock存在的問題since at least 2015。解決這個問題的唯一方法是使用if而不是switch