xpathxml-namespacesspring-mvc-test

MockHttpServletResponse : Checking xml content


I am testing a controller using MockMvc. This is what the response looks like:

MockHttpServletResponse:
              Status = 200
       Error message = null
             Headers = {Content-Type=[text/xml]}
        Content type = text/xml
                Body = <?xml version="1.0" encoding="UTF-8" standalone="yes"?><ns2:diagnosisCode xmlns:ns2="http://schemas.mycompany.co.za/health" effectiveStartDate="2014-03-05T00:00:00+02:00" effectiveEndDate="2014-03-05T23:59:59.999+02:00" diagnosisId="1"><diagnosisCodeId><codingSchemaCode>irrelevant schema</codingSchemaCode><diagnosisCode>irrelevant code</diagnosisCode></diagnosisCodeId></ns2:diagnosisCode>
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

Pretty-printed version of the Body line:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:diagnosisCode xmlns:ns2="http://schemas.mycompany.co.za/health" effectiveStartDate="2014-03-05T00:00:00+02:00" effectiveEndDate="2014-03-05T23:59:59.999+02:00" diagnosisId="1">
    <diagnosisCodeId>
        <codingSchemaCode>irrelevant schema</codingSchemaCode>
        <diagnosisCode>irrelevant code</diagnosisCode>
    </diagnosisCodeId>
</ns2:diagnosisCode>

The call on MockMvc looks like

mockMvc.perform(
        get("/diagnostic/diagnosisCodes/{schema}/{code}", IRRELEVANT_SCHEMA, IRRELEVANT_CODE).accept(MediaType.TEXT_XML))
        .andDo(print())
        .andExpect(content().contentType(MediaType.TEXT_XML))
        .andExpect(status().isOk())
        .andExpect(xpath("diagnosisCodeId/diagnosisCode").string(IRRELEVANT_CODE))
        .andExpect(xpath("diagnosisCodeId/codingSchemaCode").string(IRRELEVANT_SCHEMA));

I am pretty sure I am misunderstanding how I'm supposed to use XPath here, but why is this assertion failing? What should my expectation look like?

java.lang.AssertionError: XPath diagnosisCode expected:<irrelevant code> but was:<>

Solution

  • I'm not totally sure what the XPath context is (or whether it is the document node), but I see two possible problems and guess both apply: