Show List

Using Path Parameters

Below is a sample Java program demonstrating how to test a GET request of a REST API using JUnit and Rest Assured, passing path parameters:


import io.restassured.RestAssured; import io.restassured.response.Response; import org.junit.jupiter.api.Test; import static io.restassured.RestAssured.given; import static org.junit.jupiter.api.Assertions.assertEquals; public class ApiGetWithPathVariableTest { @Test public void testGetRequestWithPathParameters() { // Base URI of the REST API RestAssured.baseURI = "https://api.example.com"; // Path parameters String param1 = "value1"; String param2 = "value2"; // Send GET request with path parameters Response response = given() .pathParam("param1", param1) .pathParam("param2", param2) .get("/endpoint/{param1}/{param2}"); // Get and assert the response status code int statusCode = response.getStatusCode(); assertEquals(200, statusCode, "Expected status code 200"); // Get and print 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 testGetRequestWithPathParameters method as a test case.
  • We set the base URI of the REST API using RestAssured.baseURI.
  • We define path parameters (param1 and param2).
  • We send a GET request to the /endpoint/{param1}/{param2} endpoint using given().pathParam("param1", param1).pathParam("param2", param2).get("/endpoint/{param1}/{param2}"), passing the path parameters using pathParam() 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. Adjust the base URI, endpoint, and path parameters according to your API's structure.


    Leave a Comment


  • captcha text