@Test public void checkMovieTitle() { given() .queryParam("apikey", "ce613cd7") .queryParam("i", "tt0083658") .when() .get("http://www.omdbapi.com/") .then() .body("Title", equalTo( "Blade Runner")) .body("Ratings", hasSize(3)) .body("Actors", containsString("Sean Young")); }
@Test public void postMapParams() { Map<String, String> paramMap = new HashMap <String, String>(); paramMap.put("name","Alita"); paramMap.put("job","Battle Angel"); paramMap.put("id","HK-BR035"); JSONObject mapToJson = new JSONObject(paramMap); given() .contentType(ContentType.JSON).accept(ContentType.JSON) .body(mapToJson.toString()) .when() .post("https://reqres.in/api/users") .then() .statusCode(201).log().all(); }JSON Response:
{ "name": "Alita", "job": "Battle Angel", "id": "HK-BR035", "createdAt": "2021-05-26T16:37:42.348Z" }
@Test public void postExampleJSON() { JSONObject paramMap = new JSONObject(); paramMap.put("name","Alita"); paramMap.put("job","Battle Angel"); paramMap.put("id","HK-BR035"); given() .contentType(ContentType.JSON).accept(ContentType.JSON) .body(paramMap.toString()) .when() .post("https://reqres.in/api/users") .then() .statusCode(201) .log().all(); }JSON Response:
{ "name": "Alita", "id": "HK-BR035", "job": "Battle Angel", "createdAt": "2021-05-26T16:54:10.100Z" }
@DataProvider public static Object[][] movieData() { return new Object[][]{ {"tt0133093", "The Matrix","1999","Lana Wachowski"}, {"tt1375666","Inception","2010","Christopher Nolan"}, {"tt1392190","Mad Max: Fury Road","2015","George Miller"} }; }
@Test(dataProvider = "movieData") public void checkMovieData(String id, String title, String year, String director) { given() .queryParam("apikey", "ce613cd7") .queryParam("i", id) .when() .get("http://www.omdbapi.com/") .then() .body("Title", equalTo( title)) .body("Year", equalTo( year)) .body("Director", containsString(director));NOTE: The Data Provider method can exist inside the test class (as in the example above) or be referenced from another class using:
@Test(dataProvider = "locationSet", dataProviderClass = BaseTestClass.class)Where BaseTestClass.class is the class containing the Data Provider. This can be helpful for re-using a Data Provider among different tests.
@Test public void doBasicAuth() { given() .auth() .preemptive() .basic("guest", "guest") .when() .get("https://jigsaw.w3.org/HTTP/Basic/") .then() .statusCode(200); }Basic Authentication Request Data, where the Header → Authorization=Basic is the Base64 encoding of username:password
Request method: GET Request URI: https://jigsaw.w3.org/HTTP/Basic/ Proxy: <none> Request params: <none> Query params: <none> Form params: <none> Path params: <none> Headers: Authorization=Basic Z3Vlc3Q6Z3Vlc3Q = Accept=*/* Cookies: <none> Multiparts: <none> Body: <none>
@Test public void doFormAuthentication() { given() .auth() .form("user1", "pass321", new FormAuthConfig ( "/login", "username_nm", "password_nm") ) .when() .post("http://www.ultranauts.com/signin") .then() .statusCode(200) .body(containsString("Account Dashboard")); }The associated page form with inputs named username_nm & password_nm with /login action would be:
<form class="form-signin" method="post" action="/login"> <label for='username'>Username</label> <input type="text" id="username" name="username_nm" class="form-control" placeholder="Username" required="" autofocus=""> <label for='password'>Password</label> <input type="password" id="password" name="password_nm" class="form-control" placeholder="Password" required=""> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form>
@Test public void checkHtmlAsserts() { given() .get("https://www.google.com/search?q=penguin") .then() .contentType(ContentType.HTML) // Response Content-Type header is [HTML] .header("cache-control",notNullValue()) // [header name] is not a null value .statusCode(HttpStatus.SC_OK) // HTTP Response status is [200] .cookie("1P_JAR","2021-05-27-17") // Assert cookie [name] contains [value] .body("html.head.title", equalTo("penguin - Google Search")) // Page title matches a [string] .body(containsString("Spheniscidae")); // [String] exists anywhere in the body tag }
@Test public void checkJsonAsserts() { given() .get("https://neonuneon.com/php/test.json") .then() .statusCode(200) // Verify status code is OK .body("users[0].id", equalTo(5)) // Verify the 1st user's id is [5] .body("users[0].skills[1]", is("strength")) // Verify the 1st user's 2nd skill is [strength] .body("users[0].skills", hasItems("cooking","martial arts")) // Verify the 1st user's skills contain [multiple items] .body("users[1].skills", hasSize(3)) // Verify the 2nd user has [3] skill .body("users[1].skills[1]", either( // Verify the 2nd user's 2nd skill is either [type1] or [type2] is("farming")) .or(is("piloting"))); }JSON used in example:
{ "users": [ { "id": 5, "email": "leloodallas@multipass.com", "first_name": "Leloo", "last_name": "Dallas", "skills": ["martial arts","strength","cooking"] }, { "id": 97, "email": "jshadow@zorg.net", "first_name": "Jean-Baptiste", "last_name": "Zorg", "skills": ["weapons","piloting","conspiring"] } ] }
@Test public void checkXmlAssert() { given() .get("https://www.ultranauts.com/test.xml") .then() .statusCode(200) .body("users.user[0].@id", equalTo("5")) // Verify the 1st user's id is [5] .body("users.user[0].skills.skill[1]", is("strength")) // Verify the 1st user's 2nd skill is [strength] .body("users.user[0].skills.skill", hasItems("cooking","martial arts")) // Verify the 1st user's skills contain [multiple items] .body("users.user[1].skills.skill.size()", is(3)) // Verify the 2nd user has [3] skill .body("users.user[1].skills.skill[1]", either( // Verify the 2nd user's 2nd skill is either [type1] or [type2] is("farming")) .or(is("piloting"))); }XML used in example:
<users> <user id="5"> <email>leloodallas@multipass.com</email> <first_name>Leloo <last_name>Dallas <skills> <skill>martial arts</skill> <skill>strength</skill> <skill>cooking</skill> </skills> </user> <user id="97"> <email>mrshadow@zorg.net</email> <first_name>Jean-Baptiste <last_name>zorg <skills> <skill>weapons</skill> <skill>piloting</skill> <skill>conspiring</skill> </skills> </user> </users>
private static RequestSpecification reqSpec; @BeforeClass public static void createRequestSpec() { reqSpec = new RequestSpecBuilder () .setBaseUri("http://www.omdbapi.com/") .build(); }The request specification can then be used within the test:
@Test public void checkMovieWithRequestSpec() { given() .spec(reqSpec) .queryParam("i", "tt0083658") .when() .get("http://www.omdbapi.com/") .then() .body("Title", equalTo( "Blade Runner")); }
private static ResponseSpecification responseSpec; @BeforeClass public static void createResponseSpec() { responseSpec = new ResponseSpecBuilder () .expectStatusCode(200) .expectContentType(ContentType.JSON) .build(); }The Response Specification is passed after the then() keyword. Here we check the status code (200) and Content Type (JSON) using the response spec followed by verifying the body Title attribute for the individual test:
@Test public void checkMovieWithResponseSpec() { given() .queryParam("apikey", "ce613cd7") .queryParam("i", "tt0083658") .when() .get("http://www.omdbapi.com/") .then() .spec(responseSpec) .body("Title", equalTo( "Blade Runner")); }
given()Or
.contentType(ContentType.JSON) // Set the content type of the request
.accept(ContentType.JSON) // Set the expected content type of the response
http.request( GET, ContentType.JSON )
Enumeration | Content Type |
ContentType.ANY | */* |
ContentType.BINARY | application/octet-stream |
ContentType.HTML | text/html |
ContentType.JSON | application/json, application/javascript, text/javascript |
ContentType.TEXT | text/plain |
ContentType.URLENC | application/x-www-form-urlencoded |
ContentType.XML | application/xml, text/xml, application/xhtml+xml |
URL | Description |
ReqRes | A REST API for testing JSON responses |
JSON Placeholder | Another site for JSON response testing |
OMDb API | A REST API for movie data JSON & posters *Requires API Key |
JSON Server | Simple localhost server for JSON using NodeJS |
Spring Boot Login (Github) | A sample Spring boot project with various login scenarios, can be helpful for testing authentication. |