You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rest Assured+TestNG中提取并验证SOAP XML响应标签

解决Rest Assured提取SOAP响应指定XML标签的问题

问题说明

使用Rest Assured结合TestNG开展SOAP接口自动化测试时,调用xmlPath.getString("<StatusCode>")提取<ns4:StatusCode>标签值,会返回所有同名标签的内容拼接结果,无法精准获取<ns4:SendMessageElement>下的目标<ns4:StatusCode>值,需要实现精准提取并与预期值断言匹配。

解决方案

由于XML存在命名空间和同名标签,需要通过带命名空间的精准路径定位或XPath表达式来获取目标标签值,同时添加TestNG断言确保测试结果符合预期。

步骤1:注册XML命名空间

响应中ns4对应的命名空间为http://*****/uwl/ws/message/wsdl/send,soap对应的命名空间为http://schemas.xmlsoap.org/soap/envelope/,在XmlPath中注册这些命名空间,便于后续精准定位。

步骤2:精准提取目标标签值

通过层级路径或XPath表达式,定位到<ns4:SendMessageElement>下直接子节点的<ns4:StatusCode>。

步骤3:添加断言验证

使用TestNG的断言方法,将实际提取值与预期值对比,只有匹配时测试才通过。

修改后的代码示例

package testcases;

import io.restassured.RestAssured;
import io.restassured.path.xml.XmlPath;
import io.restassured.response.Response;
import org.apache.commons.io.IOUtils;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.FileInputStream;

import static io.restassured.RestAssured.given;

public class api_automation {

    @Test
    public void postMethod() throws Exception {
        FileInputStream fileinputstream = new FileInputStream("/home/intellij-projects/rest-assured/src/main/java/testcases/request.xml");
        RestAssured.baseURI = "*******";
        Response responses = given()
                .header("Content-Type", "text/xml")
                .body(IOUtils.toString(fileinputstream, "UTF-8"))
                .when()
                .post("******")
                .then()
                .statusCode(200)
                .log().all()
                .extract().response();

        // 注册XML命名空间
        XmlPath xmlPath = new XmlPath(responses.asString())
                .with("ns4", "http://*****/uwl/ws/message/wsdl/send")
                .with("soap", "http://schemas.xmlsoap.org/soap/envelope/");

        // 方式1:通过层级路径提取目标值
        String statusCode = xmlPath.getString("soap:Envelope.soap:Body.ns4:SendMessageElement.ns4:StatusCode");
        
        // 方式2:通过XPath表达式提取(二选一即可)
        // String statusCode = xmlPath.getString("//ns4:SendMessageElement/ns4:StatusCode");

        System.out.println("Status Code is " + statusCode);

        // 断言验证:与预期值匹配
        String expectedStatusCode = "Success-2000";
        Assert.assertEquals(statusCode, expectedStatusCode, "StatusCode与预期不符");
    }
}

备选方案(无需注册命名空间)

如果不想注册命名空间,可以使用XPath的local-name()方法匹配标签名,并通过索引指定第一个匹配节点:

String statusCode = xmlPath.getString("//*[local-name()='SendMessageElement']/*[local-name()='StatusCode'][1]");

内容的提问来源于stack exchange,提问作者RuqiJam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:20:35