Challenge 3 rest-assured

Cách 1: lấy thông tin trực tiếp

@Test
void name1() {  
	Response res = given()
          .get("https://auto-test-challenges.herokuapp.com/challenge3restassured"); (1)
  	Map<String, ?> data = res.jsonPath().getMap("data"); (2)
  	Set<String> keys = data.keySet(); (3)

  	int sum = keys.stream()
          .mapToInt(key ->
                  JsonPath.read(res.asString(), String.format("$.data[\"%s\"].number", key)))
          .sum(); (4)
  	System.out.println(sum); //60
}
  • (1) Lấy response
  • (2) Lưu những object con vào thành Map
  • (3) Tách lấy key của Map
  • (4) Với từng key, lấy thông tin number

Cách 2: mapping response vào POJO

import lombok.Data;

@Data
public class DataExample {
    public int number;
    public Map<String, Integer> data;
}
@Test
void name2() {
    Response res = given()
            .get("https://auto-test-challenges.herokuapp.com/challenge3restassured"); (1)

    Configuration configuration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider())
            .mappingProvider(new JacksonMappingProvider())
            .build(); (2)

    List<DataExample> data = JsonPath.using(configuration).parse(res.asString())
            .read("$.data.*", new TypeRef<>() {}); (3)

    int sum = data.stream().mapToInt(DataExample::getNumber).sum(); (4)
    System.out.println(sum); //60
}
  • (1) Lấy response
  • (2) set mapper jackson cho jsonpath
  • (3) Lưu toàn bộ các objet thành List<DataExample>
  • (4) Từ List<DataExample> tách lấy number và tính tổng sử dụng stream java8

Lưu ý: 2 cách trên sử dụng các thư viện sau:

pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
</dependency>
0 0 votes
Đánh giá challenge
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments