Show List

Request Specification Builder

Below is an example Java program that demonstrates how to use Rest Assured with Request Specification Builder and JUnit to test a GET request to a REST API endpoint:


import io.restassured.RestAssured; import io.restassured.builder.RequestSpecBuilder; import io.restassured.response.Response; import io.restassured.specification.RequestSpecification; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; public class ApiGetTestWithRequestSpecBuilderJUnit { @Test public void testGetRequest() { // Build request specification RequestSpecification requestSpec = new RequestSpecBuilder() .setBaseUri("https://jsonplaceholder.typicode.com") .build(); // Send GET request using request specification Response response = given() .spec(requestSpec) .get("/posts/1"); // Get and assert the response status code int statusCode = response.getStatusCode(); assertEquals(200, statusCode, "Expected status code 200"); // Get and assert the response body String responseBody = response.getBody().asString(); System.out.println("Response Body:"); System.out.println(responseBody); } }

In this example:

  • We import JUnit's @Test annotation and assertEquals method for assertions.
  • We use the @Test annotation to mark the testGetRequest method as a test case.
  • We build the request specification using the RequestSpecBuilder and set the base URI using setBaseUri().
  • We send a GET request to the /posts/1 endpoint using given().spec(requestSpec).get("/posts/1"), passing the request specification to the given() method.
  • We assert the response status code using JUnit's assertEquals method.
  • We retrieve and print the response body.

Ensure that you have Rest Assured, JUnit, and its dependencies added to your project's classpath. You can run this test case using JUnit test runner. Additionally, you may need to handle exceptions such as IOException or NullPointerException depending on your specific requirements and error handling strategy.


    Leave a Comment


  • captcha text