简体   繁体   中英

RestAssured - how to check id in <a id=“some number”></a>?

I am testing a web service, which returns an xml like in the example below

<test xmlns="some url">
   <a id="482b6f66-0543-49b2-9a22-d70dc1a87032" href="some url">some text</a>
</test>

I looked through RestAssured documentation but I could not find how to check individual xml properties. I want to test "id" property, returned in the response, but my test fails, telling me that actual vs expected is empty, though I can clearly see that the tag is there and id value is present, if I output xml response as a String.

Here's my test:

expect().body("test.a.id", equalTo(expectedId)).when().post(myRequest);

您错过了@应该是:

expect().body("test.a.@id", equalTo(expectedId)).when().post(myRequest);

Since your response is XML you can use XPath:

expect().body(hasXPath("/test/a/@id"), equalTo(expectedId)).when().post(myRequest);

@ is the way you should address attributes in xpath. Note that this might also help you with a solution using XMLPath. (see the examples here )

Perhaps your usage of namespaces might give some troubles though, you can enable that using:

given().
    config(newConfig().xmlConfig(xmlConfig().with().namespaceAware(true))).
expect().
    body(hasXPath("/yourns:test/yourns:a/@id"), equalTo(expectedId)).when().post(myRequest);

see also: http://code.google.com/p/rest-assured/wiki/Usage#XPath

The solution turned out to be a bit ugly, but I could not find any relevant examples of this usage, so it's all a guess work. Maybe there's a better way, but here's what I came up with:

Here's the code to find and print my id:

String xml = get(myRequest).asString();
XmlPath xmlPath = new XmlPath(xml).setRoot("test");
String id = xmlPath.get("a.@id");
Assert.assertTrue(id.equals(expectedId));

This worked for me with xml:

<example id="12345">
    <someStuff></someStuff>
</example>

I could verify the attribute using:

given().
when().
    post("/example/get/").
then().
    body(
        "example.@id", equalTo("12345")
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM