我使用JUnit和Mockito来测试我的SOAP web服务是否能够优雅地处理SOAP故障,并且不会抛出任何不需要的异常,例如。
因此,到目前为止,正如您从下面的代码中看到的,我只测试是否抛出了SOAPFaultException
(当然是的,我抛出了它)。我想知道如何在接收到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);
}
}
我建议您使用全栈mock(即在本地套接字上生成一个Endpoint,将客户端指向那里)。然后创建一个soap错误,让mock通过连线抛出一个适当的异常。如果您使用的是CXF,我已经创建了一个简单的JUnit规则来实现这一点,请参阅测试方法SoapServiceRuleTest.processSoapCallWithException()。
作为一种通用策略,我建议您进行一个抽象的"快乐案例"单元测试,然后通过对每个测试方法的mock进行重置并相应地添加thenThrow(..),一次破坏一个调用。