Show List
Using Query Parameters
Below is a sample Java program demonstrating how to test a GET request of a REST API using JUnit and Rest Assured, passing query 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 ApiGetWithQueryParametersTest {
@Test
public void testGetRequestWithQueryParameters() {
// Base URI of the REST API
RestAssured.baseURI = "https://api.example.com";
// Query parameters
String param1 = "value1";
String param2 = "value2";
// Send GET request with query parameters
Response response = given()
.queryParam("param1", param1)
.queryParam("param2", param2)
.get("/endpoint");
// 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
@Testannotation andassertEqualsmethod for assertions. - We use the
@Testannotation to mark thetestGetRequestWithQueryParametersmethod as a test case. - We set the base URI of the REST API using
RestAssured.baseURI. - We define query parameters (
param1andparam2). - We send a GET request to the
/endpointendpoint usinggiven().queryParam("param1", param1).queryParam("param2", param2).get("/endpoint"), passing the query parameters usingqueryParam()method. - We assert the response status code using JUnit's
assertEqualsmethod. - 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 query parameters according to your API's structure.
Leave a Comment