title: How to use Mockito to test SOAP messages?
body: <p>I'm fairly new to Mockito, and figured I would try to use it to test a SOAP Handler.  However, this is turning out to be a much more painful than I would have expected/desired.</p>
  
  <p>I'm looking to validate that my handler is able to extract the messageID in the header of a SOAPMessage.  However, from the handler, the only way to get to the header is via the context/message/part/envelope/header.  Using Mockito my solution was to mock my SOAPMessage, meant creating each individual object, and stubbing the method.</p>
  
  <p>I can only imagine that there is an easier/cleaner way of accomplishing this:</p>
  
  <pre><code>@RunWith(MockitoJUnitRunner.class)
  public class UUIDHandlerTest {
  
      @Mock private SOAPMessage message;
      @Mock private SOAPEnvelope envelope;
      @Mock private SOAPHeader header;
      @Mock private SOAPPart part;
  
      @Mock
      private SOAPMessageContext context;
  
      @Before
      public void setup() throws SOAPException{
          when( context.getMessage()).thenReturn(message);
          when( message.getSOAPPart()).thenReturn(part);
          when( part.getEnvelope()).thenReturn(envelope);
          when( envelope.getHeader()).thenReturn(header);
      }
  
  
      @Test
      public void testHandleInboundMessage() {
          when( context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).thenReturn(false);
  
          when(header.getElementsByTagName(anyString())).thenAnswer(new Answer&lt;NodeList&gt;() {
              /* (non-Javadoc)
               * @see org.mockito.stubbing.Answer#answer(org.mockito.invocation.InvocationOnMock)
               */
              @Override
              public NodeList answer(InvocationOnMock invocation) throws Throwable {
                  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                  DocumentBuilder db = dbf.newDocumentBuilder();
                  Document doc = db.parse(new ByteArrayInputStream(new String("&lt;wsa:MessageID&gt;messageId&lt;/wsa:MessageID&gt;").getBytes()));
  
                  // TODO Auto-generated method stub
                  return doc.getElementsByTagName("wsa:MessageID");
              }
  
          });
  
  
          // call the test class
          new UUIDHandler().handleMessage(context);
  
          // check the MDC value
          assertEquals("messageId", MDC.get(LoggerConstants.DC_PROPERTY_MESSAGE_ID));
      }
  }
  </code></pre>
  
  <p>Like I said, it works, but it looks like a very ugly/heavy weight solution.</p>
  
  <p>Is there anyway to do this easier/cleaner?</p>
  
  <p>Thanks!</p>
  
  <p>Eric</p>