[英]Rest Assured: extract value from Response List
I have a List returned as response.我有一个列表作为响应返回。 I need to get one item from list using product.name and tariffPlan.name.我需要使用产品名称和关税计划名称从列表中获取一项。
[
{
"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"
}
}
]
I use Java8.我使用Java8。 Here is my method.这是我的方法。 I got List of Card.class elements.我得到了 Card.class 元素列表。 And then I need to get single Item from list with specified "product.name" and "tariffPlan.name".然后我需要从具有指定“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);
}
Is it possible to do it with restAssured?是否可以通过 restAssured 来实现? Maybe use .param method like in my example?也许在我的例子中使用 .param 方法? But in my example .param method is ignored.但在我的示例中 .param 方法被忽略。 Thank you for your ideas.谢谢你的想法。
UPD.更新。 My decision is:我的决定是:
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();
}
If you need to get a value from response json list, here's what worked for me:如果您需要从响应 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")
Actually, you can but... you need to handle deserialization issue of default mapper becase if you try do the following:实际上,您可以但是...如果您尝试执行以下操作,则需要处理默认映射器的反序列化问题:
.extract().jsonPath().getList("findAll {it.productName == " + productName + "}", Card.class);
You will failing on converting HashMap to your object type.您将无法将 HashMap 转换为您的对象类型。 It happens because of using gpath expression in path provides json without double quotes on keys by default.发生这种情况是因为在 path 中使用 gpath 表达式提供了默认情况下在键上没有双引号的 json。 So you need to prettify it with (you can put it in RestAssured
defaults):所以你需要美化它(你可以把它放在RestAssured
默认值中):
.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
And as result your would be able to cast things like that:结果你将能够投射这样的东西:
.getObject("findAll {it.productName == 'productName'}.find {it.tariffPlanName.contains('tariffPlanName')}", Card.class)
See full example:查看完整示例:
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;
}
}
Suppose you want to fetch the value of the id, when product name is "Credit" and tariffPlan is "Gold".假设您要获取 id 的值,当产品名称为“Credit”且关税计划为“Gold”时。
Use采用
from(get(url).asString()).getList("findAll { it.product.name == 'Credit' && it.tariffPlan.name == 'Gold'}.id");
Where url - http/https request and get(url).asString()
will return a JSON response as string.其中 url - http/https 请求和get(url).asString()
将以字符串形式返回 JSON 响应。
Here a kotlin example:这是一个 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.