Show List
Using Headers and Cookies
Below is a sample Java program demonstrating how to test a GET request of a REST API using JUnit and Rest Assured, including headers and cookies:
import io.restassured.RestAssured;
import io.restassured.http.Cookie;
import io.restassured.http.Cookies;
import io.restassured.http.Header;
import io.restassured.http.Headers;
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 ApiGetWithHeadersAndCookiesTest {
@Test
public void testGetRequestWithHeadersAndCookies() {
// Base URI of the REST API
RestAssured.baseURI = "https://api.example.com";
// Headers
Header header1 = new Header("HeaderName1", "HeaderValue1");
Header header2 = new Header("HeaderName2", "HeaderValue2");
Headers headers = new Headers(header1, header2);
// Cookies
Cookie cookie1 = new Cookie.Builder("CookieName1", "CookieValue1").build();
Cookie cookie2 = new Cookie.Builder("CookieName2", "CookieValue2").build();
Cookies cookies = new Cookies(cookie1, cookie2);
// Send GET request with headers and cookies
Response response = given()
.headers(headers)
.cookies(cookies)
.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
@Test
annotation andassertEquals
method for assertions. - We use the
@Test
annotation to mark thetestGetRequestWithHeadersAndCookies
method as a test case. - We set the base URI of the REST API using
RestAssured.baseURI
. - We define headers (
HeaderName1
,HeaderValue1
,HeaderName2
,HeaderValue2
) using theHeader
class. - We define cookies (
CookieName1
,CookieValue1
,CookieName2
,CookieValue2
) using theCookie
class. - We send a GET request to the
/endpoint
endpoint usinggiven().headers(headers).cookies(cookies).get("/endpoint")
, passing the headers and cookies usingheaders()
andcookies()
methods. - 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, headers, and cookies according to your API's structure.
Leave a Comment