如何为Junit测试用例编写xPath

时间:2021-02-23 05:09:40

I have following XML string, How to write XPath to get value "rest/accounts/123"

我有以下XML字符串,如何编写XPath以获取值“rest / accounts / 123”

<?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>

I am trying to write JUnit test case

我正在尝试编写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")));

but line

MockMvcResultMatchers.xpath("/account/atom:link/href()").string( Matchers.containsString("/rest/accounts/123")))

is throwing error.

投掷错误。

As per suggestions I changed code as

根据建议,我将代码更改为

 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 test case giving error

Junit测试用例给出错误

com.sun.org.apache.xpath.internal.domapi.XPathStylesheetDOM3Exception: Prefix must resolve to a namespace: atom

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

1 个解决方案

#1


0  

You can use the substring-after function:

您可以使用substring-after函数:

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

#1


0  

You can use the substring-after function:

您可以使用substring-after函数:

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