多协议封装(java)
多种类型的响应全部转换为标准的json进行断言
<!-- 直接将xml转换成字符串json-->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.14.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${json-path.version}</version>
</dependency>
package com.restassured;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MulitiResqTest {
//针对json完成断言
@Test
void testJsonResq() {
//问题:不知道返回值的格式类型
//解决办法:在获取返回值之前,都调用一下格式转换方法,保证所有返回值类型都为json或者其他统一格式
String jsonRes= given()
.relaxedHTTPSValidation()
.when()
.get("https://httpbin.ceshiren.com/get")
.then()
.log().all()
.extract().body().asString();
String res = mulitiResToJson(jsonRes);
System.out.println("res:" + res);
List<String> hosts= JsonPath.read(res,"$..Host");
assertEquals("httpbin.ceshiren.com",hosts.get(0));
}
public static String mulitiResToJson(String originRes) {
String res = "";
//判断返回值类型格式
//xml转换为json
if (originRes.startsWith("<?xml")){
XmlMapper xmlMapper = new XmlMapper();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode node;
try {
node = xmlMapper.readTree(originRes.getBytes());
res = objectMapper.writeValueAsString(node);
} catch (IOException e) {
throw new RuntimeException(e);
}
}else {
res=originRes;
}
return res;
}
//问题:格式的转换依然需要在用例中进行调用?
//解决方法:把转换的过程封装到filter中
//针对xml完成断言
@Test
void testXmlResq() {
//String
String xmlResqBody = given()
.relaxedHTTPSValidation()
.when()
.get("https://www.nasa.gov/rss/dyn/lg_image_of_the_day.rss")
.then().extract().body().asString();
String res = mulitiResToJson(xmlResqBody);
System.out.println("res:" + res);
List<String> titles=JsonPath.read(res,"$..title");
System.out.println("titles:"+titles);
assertEquals("NASA Image of the Day",titles.get(0));
}
}