2016-02-14 110 views
0

我有以下XML字符串, 如何编写XPath来获取价值“休息/账户/ 123”如何编写JUnit测试案例的XPath

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<account xmlns:atom="http://www.w3.org/2005/Atom"> 
    <atom:link rel="self" href="http://localhost/rest/accounts/123"/> 
    <name>satya</name> 
    <password>123</password> 
</account> 

我想写JUnit测试用例

mockMvc.perform(get("/rest/accounts/123") 
     .contentType(MediaType.APPLICATION_JSON) 
     .accept(MediaType.APPLICATION_XML)) 
      .andDo(print()) 
      .andExpect(MockMvcResultMatchers.status().isOk()) 
      .andExpect(xpath("/account/atom:link/href()") 
       .string(containsString("/rest/accounts/123"))) 
      .andExpect(xpath("/account/name/text()").string(equalTo("satya"))); 

但线

MockMvcResultMatchers.xpath。( “/帐户/原子:链路/ HREF()”)的字符串( 匹配ers.containsString(“/ rest/accounts/123”)))

出现错误。

按照建议我改变代码

mockMvc.perform(
       MockMvcRequestBuilders.get("/rest/accounts/123").contentType(MediaType.APPLICATION_JSON) 
         .accept(MediaType.APPLICATION_XML)) 

       .andDo(print()) 
       .andExpect(MockMvcResultMatchers.status().isOk()) 
       .andExpect(
         MockMvcResultMatchers.xpath("/account/atom:link/@href,").string(
           Matchers.containsString("/rest/accounts/123"))) 
       .andExpect(MockMvcResultMatchers.xpath("/account/name/text()").string(Matchers.equalTo("satya"))); 

     // .andExpect(MockMvcResultMatchers.jsonPath("$.links[*].href").exists()); 
    } 

JUnit测试案例给错误

com.sun.org.apache.xpath.internal.domapi.XPathStylesheetDOM3Exception: 前缀必须解析命名空间:原子

+0

'HREF()'应该是'@ href' – trincot

+0

我在JUnit改变代码,但得到错误运行 – Satya

回答

0

您可以使用substring-after函数:

substring-after(//atom:link/@href, "http://localhost/") 
+0

将上面的修改仍然得到JUnit测试用例的错误,如问题如上图所示 – Satya

+0

@Satya后:我不是熟悉你使用的库。我回答了原来的问题。也许你需要注册'atom'命名空间? – choroba