I am trying to print out the status code 200 on console and pass either the 404 or 200 status code the methods below for testing purpose, the API code is hitting and returning a success message, but I do not know how to print out the 200 or 404 status Code on console. as well to pass the status code the method below. Any help is appreciated. Thanks.
@Test
public void getRequest() {
given().baseUri("https://api.publicapis.org/entries")
.when().get()
.then().assertThat().statusCode(200).extract().response().asString();}
// How can I pass the 200 response code from this to the methods below? // Also how can we print out the status code on console?
// I check the response code is 200:
public static void checkResponseCode(String expectedResponse){
ValidateResponse(expectedResponse);
}
public static String GetResponseCode() {
return responseSpecification.response().toString();
}
public static void ValidateResponse(String expectedResponse){
String responseCode = GetResponseCode();
switch (expectedResponse) {
case "200 OK":
Assert.assertEquals("OK", responseCode, "Request Failed:" responseCode);
break;
case "404 Not Found":
Assert.assertEquals("Not Found", responseCode, "Request Failed:" responseCode);
default:
throw new IllegalArgumentException(expectedResponse " is not found in switch case options");
}
}
CodePudding user response:
This code should help you to get the status code:
ResultActions perform = mockMvc.perform(get("/getRecords")
.param("start", start)
// validation
perform.andExpect(status().isOk())
.andExpect(content().json(expectedContent));
// getting a response object for future needs
MvcResult mvcResult = perform.andReturn();
// getting HTTP status code, response code:
int status = mvcResult.getResponse().getStatus();
// just to see it.
System.out.println("status = " status);
You can see above how I am getting MvcResult and extracting the status code value out of it.
CodePudding user response:
You can use the getStatusCode()
method in io.restassured.response.Response
. It will return status code as a int
.
public static int GetResponseCode() {
Response response = given()
.when()
.get(url)
.then()
.extract().response();
return response.getStatusCode();
}