3

我正在使用MockMvc. 这是响应的样子:

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 = []

该行的精美印刷版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>

通话MockMvc看起来像

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));

我很确定我误解了我应该如何在这里使用 XPath,但是为什么这个断言会失败?我的期望应该是什么样的?

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

2 回答 2

2

我不完全确定 XPath 上下文是什么(或者它是否是文档节点),但我看到两个可能的问题并且猜测两者都适用:

  • 您尝试匹配< diagnosisCodeId/>作为根元素的元素。没有,但他们是<diagnosisCode>. 要么包括根节点的轴步骤(可能更好的方法),要么在查询前面使用descendant-or-self轴步骤。//

    /diagnosisCode/diagnosisCodeId/diagnosisCode
    //diagnosisCodeId/diagnosisCode
    
  • 该文档使用名称空间(用于根元​​素)。除了上面描述的根元素问题之外,要么注册该命名空间(更好的解决方案,但我不知道如何在 Spring MVC 中执行此操作),要么使用以下解决方法忽略它:

    /*[local-name() = 'diagnosisCode']/diagnosisCodeId/diagnosisCode
    

    首先匹配所有子节点,然后限制为具有适当元素名称的子节点(忽略命名空间)。

    通过添加 XPath 2.0 支持(例如通过将 Saxon 包含为 library),您还可以使用通配符命名空间匹配器:

    /*:diagnosisCode/diagnosisCodeId/diagnosisCode
    

    如果您将命名空间 URI 注册http://schemas.mycompany.co.za/healthns2,则查询将如下所示

    /ns2:diagnosisCode/diagnosisCodeId/diagnosisCode
    
于 2014-03-05T22:24:34.670 回答
1

有一个重载xpath需要一个Map<String, String>命名空间:

Map<String, String> ns = Map.of("ns2", "http://schemas.mycompany.co.za/health");
mockMvc.perform(get("/diagnostic/diagnosisCodes/{schema}/{code}", IRRELEVANT_SCHEMA, IRRELEVANT_CODE)
        .accept(MediaType.TEXT_XML))
        .andExpect(xpath("ns2:diagnosisCodeId/diagnosisCode", ns).string(IRRELEVANT_CODE))
        .andExpect(xpath("ns2:diagnosisCodeId/codingSchemaCode", ns).string(IRRELEVANT_SCHEMA));
于 2019-10-10T09:34:33.297 回答