2016-03-23 41 views
1

我正在使用JUnit和Mockito來測試我的SOAP Web服務是否正常處理SOAP錯誤,並且不會拋出任何不需要的例外情況。因此,直到現在,從下面的代碼中可以看出,我只測試SOAPFaultException是否正在被拋出(當然是,我拋出了它)。我想知道如何檢查接收SOAP錯誤時是否會引發其他異常。如何檢查SOAP錯誤是否正在被正常處理?

也有什麼辦法模擬SOAP錯誤而不會引發異常(SOAPFaultException)?

public class SOAPFaultsTest { 

private MyObj myObj = (MyObj) mock(IMockClass.class); 

@Before 
public void create() { 

    SOAPFault soapFault = null; 
    try { 
     soapFault = SOAPFactory.newInstance(SOAPConstants.SOAP_1_1_PROTOCOL).createFault(); 
     soapFault.setFaultString("unable to create new native thread"); 
     soapFault.setFaultCode(QName.valueOf("soap:Server")); 
    } catch (SOAPException e) { 
     e.printStackTrace(); 
    } 

    // Define behaviour of myObj mock object 
    when(myObj.randomMethod(any(RandomClass.class))).thenThrow(new SOAPFaultException(soapFault)); 
} 

// Here I'm testing whether invoking myObj's randomMethod with a RandomClass object as an argument throws a SOAPFaultException. 
// It does because this is how I defined its behaviour. 
// What I really want to test is whether receiving a SOAP fault at any time is going to cause any trouble. 
@Test(expected=SOAPFaultException.class) 
public void testSOAPException() throws SOAPFaultException { 
    RandomClass rc = new RandomClass(); 
    myObj.randomMethod(rc); 
} 
} 

回答

0

我建議你去一個全棧模擬(即在本地套接字上產生一個端點,指向那裏的客戶端)。然後創建一個肥皂故障,讓模擬器通過導線扔appropriate exception。如果您使用的是CXF,我創建了simple JUnit Rule這樣做,請參閱測試方法SoapServiceRuleTest.processSoapCallWithException()。作爲一般策略,我建議你做一個抽象的「快樂案例」單元測試,然後通過對每個測試方法進行模擬重置並相應地添加thenThrow(..)來一次破壞一個調用。

相關問題