簡體   English   中英

放心:從響應列表中提取值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM