4.Method is using OOPs concepts.In this method we pass objects of a class as post. But what kind of variables we define in an object depends upon the body of the post request.Lets understand with few examples If the body is like the one below
Body:
{
"firstName": "hs",
"lastName": "d",
"email": "dsd@example.com",
"programme": "Computer Science",
"courses": [
"Java",
"Angular",
"Mongo db"
]
}
Then we make an object of student that has variables like firstName, lastName etc and.Also contains a list named courses.Since courses is just a normal list above so we add courses as a list in Student class below.
package postreqopps;
import java.util.ArrayList;
import java.util.List;
public class Student {
public String firstName;
public String lastName;
public String email;
public String programme;
public List<String> courses;
public Student(String firstName, String lastName, String email, String programme) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.programme = programme;
this.courses = new ArrayList<String>();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProgramme() {
return programme;
}
public void setProgramme(String programme) {
this.programme = programme;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(String course) {
courses.add(course);
}
}
And then we pass this student object to post request like this
package postreqopps;
import static io.restassured.RestAssured.given;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
public class PostReqObjectExample {
@Test
public void test001() {
RestAssured.baseURI = "http://localhost";
RestAssured.port = 8080;
RestAssured.basePath = "/student";
Student student = new Student("hsdfds","dhffn","ddhhdhd@gmail.com","Computer Science");
student.setCourses("Java");
student.setCourses("Angular");
student.setCourses("Mongo db");
Response resp = given().contentType(ContentType.JSON).log().body().body(student).post();
resp.prettyPrint();
}
}