【问题标题】:How to write xPath for Junit test case如何为 Junit 测试用例编写 xPath
【发布时间】:2016-02-14 18:10:13
【问题描述】:

我有以下 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>

我正在尝试编写 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("/account/atom:link/href()").string( Matchers.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: 前缀必须解析为命名空间:atom

【问题讨论】:

    标签: xml spring-mvc xpath junit mockito


    【解决方案1】:

    你可以使用substring-after函数:

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

    【讨论】:

    • 添加上述更改后仍然出现如上所示的Junit测试用例错误
    • @Satya:我不熟悉您使用的库。我回答了原来的问题。也许您需要注册atom 命名空间?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2017-09-06
    • 2019-06-21
    相关资源
    最近更新 更多