Michael answers very closely, but here is an example that works.
I already use Mockito for my unit tests, so I am familiar with the library. However, unlike my previous experience with Mockito, just mocking the result of the return does not help. I need to do two things to check all use cases:
- Change the value stored in StreamResult.
- Throw a SoapFaultClientException.
First, I needed to understand that I could not scoff at WebServiceTemplate with Mockito, since this is a specific class (you need to use EasyMock, if necessary). Fortunately, a call to the sendSourceAndReceiveToResult web service is part of the WebServiceOperations interface. This required a change in my code in order to expect WebServiceOperations and WebServiceTemplate.
The following code supports the first use case when the result is returned in the StreamResult parameter:
private WebServiceOperations getMockWebServiceOperations(final String resultXml) { WebServiceOperations mockObj = Mockito.mock(WebServiceOperations.class); doAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { try { Object[] args = invocation.getArguments(); StreamResult result = (StreamResult)args[2]; Writer output = result.getWriter(); output.write(resultXml); } catch (IOException e) { e.printStackTrace(); } return null; } }).when(mockObj).sendSourceAndReceiveToResult(anyString(), any(StreamSource.class), any(StreamResult.class)); return mockObj; }
Support for the second use case is similar, but requires throwing an exception. The following code throws a SoapFaultClientException that contains a faultString. The error code is used by the code I'm testing, which processes the web service request:
private WebServiceOperations getMockWebServiceOperations(final String faultString) { WebServiceOperations mockObj = Mockito.mock(WebServiceOperations.class); SoapFault soapFault = Mockito.mock(SoapFault.class); when(soapFault.getFaultStringOrReason()).thenReturn(faultString); SoapBody soapBody = Mockito.mock(SoapBody.class); when(soapBody.getFault()).thenReturn(soapFault); SoapMessage soapMsg = Mockito.mock(SoapMessage.class); when(soapMsg.getSoapBody()).thenReturn(soapBody); doThrow(new SoapFaultClientException(soapMsg)).when(mockObj).sendSourceAndReceiveToResult(anyString(), any(StreamSource.class), any(StreamResult.class)); return mockObj; }
Both of these use cases may require additional code, but they work for my purposes.
Kevin
source share