![](/img/trans.png)
[英]How to validate a response and extract a value from Response body in Rest Assured?
[英]Rest Assured: extract value from Response List
我有一个列表作为响应返回。 我需要使用产品名称和关税计划名称从列表中获取一项。
[
{
"id": 123,
"product": {
"id": 1,
"code": "credit",
"name": "Credit"
},
"tariffPlan": {
"id": 1,
"code": "gold",
"name": "Gold"
}
},
{
"id": 234,
"product": {
"id": 2,
"code": "debit",
"name": "Debit"
},
"tariffPlan": {
"id": 1,
"code": "gold",
"name": "Gold"
}
}
]
我使用Java8。 这是我的方法。 我得到了 Card.class 元素列表。 然后我需要从具有指定“product.name”和“tariffPlan.name”的列表中获取单个项目。
public List<Card> getCardId(String productName, String tariffPlanName) {
return given()
.param("product.name", productName)
.param("tariffPlan.name", tariffPlanName)
.when().get("/").then()
.extract().jsonPath().getList("", Card.class);
}
是否可以通过 restAssured 来实现? 也许在我的例子中使用 .param 方法? 但在我的示例中 .param 方法被忽略。 谢谢你的想法。
更新。 我的决定是:
public Card getCard(String productName, String tariffPlanName) {
List<Card> cardList = given()
.when().get("/").then()
.extract().jsonPath().getList("", Card.class);
return cardList.stream()
.filter(card -> card.product.name.equals(productName))
.filter(card -> card.tariffPlan.name.equals(tariffPlanName))
.findFirst()
.get();
}
如果您需要从响应 json 列表中获取值,这对我有用:
Json sample:
[
{
"first": "one",
"second": "two",
"third": "three"
}
]
Code:
String first =
given
.contentType(ContentType.JSON)
.when()
.get("url")
.then()
.extract().response().body().path("[0].first")
实际上,您可以但是...如果您尝试执行以下操作,则需要处理默认映射器的反序列化问题:
.extract().jsonPath().getList("findAll {it.productName == " + productName + "}", Card.class);
您将无法将 HashMap 转换为您的对象类型。 发生这种情况是因为在 path 中使用 gpath 表达式提供了默认情况下在键上没有双引号的 json。 所以你需要美化它(你可以把它放在RestAssured
默认值中):
.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
结果你将能够投射这样的东西:
.getObject("findAll {it.productName == 'productName'}.find {it.tariffPlanName.contains('tariffPlanName')}", Card.class)
查看完整示例:
import com.google.gson.GsonBuilder;
import io.restassured.http.ContentType;
import io.restassured.mapper.factory.GsonObjectMapperFactory;
import lombok.Data;
import org.testng.annotations.Test;
import java.util.HashMap;
import java.util.List;
import static io.restassured.RestAssured.given;
public class TestLogging {
@Test
public void apiTest(){
List<Item> list = given()
.contentType(ContentType.JSON)
.when()
.get("https://jsonplaceholder.typicode.com/posts")
.then().log().all()
.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
.getList("findAll {it.userId == 6}.findAll {it.title.contains('sit')}", Item.class);
list.forEach(System.out::println);
}
@Data
class Item {
private String userId;
private String id;
private String title;
private String body;
}
}
假设您要获取 id 的值,当产品名称为“Credit”且关税计划为“Gold”时。
采用
from(get(url).asString()).getList("findAll { it.product.name == 'Credit' && it.tariffPlan.name == 'Gold'}.id");
其中 url - http/https 请求和get(url).asString()
将以字符串形式返回 JSON 响应。
这是一个 kotlin 示例:
@Test
fun `creat endpoint with invalid payload should return 400 error`() {
val responseError: List<ErrorClass> = Given {
spec(requestSpecification)
body(invalidPayload)
} When {
post("/endpoint")
} Then {
statusCode(HttpStatus.SC_BAD_REQUEST)
} Extract {
body().`as`(object : TypeRef<List<ErrorClass>>() {})
}
responseError shouldHaveSize 1
responseError[0].field shouldBe "xxxx"
responseError[0].message shouldBe "xxx"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.