如何检查是否正在正常处理SOAP错误?

时间:2016-03-23 13:00:52

标签: soap junit mockito soapfault

我正在使用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);
}
}

1 个答案:

答案 0 :(得分:0)

我建议你使用全栈模拟(即在本地套接字上生成端点,将客户端指向那里)。然后创建一个肥皂故障,让模拟器在电线上抛出appropriate exception。如果您正在使用CXF,我已创建simple JUnit Rule来执行此操作,请参阅测试方法SoapServiceRuleTest.processSoapCallWithException()

作为一般策略,我建议你做一个抽象的快乐案例'单元测试,然后你通过使用每个测试方法在模拟上重置并相应地添加thenThrow(..)来一次破坏一个调用。