Files
RestAssured/src/test/java/zacksolutions/DayFour/ParsingJSONResDataTest.java
T
2024-10-10 11:03:26 -04:00

94 lines
2.8 KiB
Java

package zacksolutions.DayFour;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.List;
import static io.restassured.RestAssured.given;
import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.equalTo;
public class ParsingJSONResDataTest {
@Test
void JSONResData(){
given()
.contentType(ContentType.JSON)
.when()
.get("http://localhost:3000/store/")
.then()
.statusCode(200)
.header("Content-Type", "application/json")
.body("books[2].Name", equalTo("The Lord of the Rings"));
}
@Test
void returnBooks(){
// Create JSON object for the book data
JSONObject data = new JSONObject();
data.put("Author", "George R. R. Martin");
data.put("Category", "Fantasy");
data.put("SerialNum", "D34C");
data.put("Price", 14.99);
data.put("Name", "A Song Of Ice and Fire");
//post the book to the server
given().contentType("text/plain; charset=utf-8")
.body(data.toString())
.when().post("http://localhost:3000/store/books")
.then().statusCode(201)
.body("Price", equalTo(14.99f))
.log().all();
}
@Test
void getTitleJSONOBJECT(){
Response res =
given()
.contentType(ContentType.JSON)
.when()
.get("http://localhost:3000/store/");
JSONObject jsonObject = new JSONObject(res.asString());
int length = jsonObject.getJSONArray("books").length();
boolean status = false;
for (int i = 0; i < length; i++) {
String title = jsonObject.getJSONArray("books").getJSONObject(i).get("Name").toString();
//System.out.println("Books number " + i + " is " + title);
if (title.equalsIgnoreCase("1984")){
status = true;
break;
}
}
Assert.assertTrue(status);
/*
List<String> booksTitle = new JsonPath(res.asString()).getList("Name");
for (String title : booksTitle) {
System.out.println(title);
}
*/
}
@Test
void getPrices(){
Response res = given()
.contentType(ContentType.JSON)
.when().get("http://localhost:3000/store/");
JSONObject jsonObject = new JSONObject(res.asString());
int numOfBooks = 0;
for (int i = 0; i < jsonObject.getJSONArray("books").length(); i++) {
String title = jsonObject.getJSONArray("books").getJSONObject(i).get("Name").toString();
double price = jsonObject.getJSONArray("books").getJSONObject(i).getDouble("Price");
if (price >10.00){
System.out.println(title);
numOfBooks ++;
}
}
System.out.println(numOfBooks);
}
}