Rest-Assured Hello World - Getting started using simple example
Overview
In previous chapter we implemented REST web service to return either xml or JSON depending on some user parameter using ContentNegotiation parameter. In this chapter we test the same webservice using Rest-Assured.What is Rest-Assured ?
Testing and validating REST services in Java is harder than in dynamic languages such as Ruby and Groovy. REST Assured brings the simplicity of using these languages into the Java domain. It eliminates the requirement of using boiler-plate code to test complex API responses, and supports both XML and JSON.Lets Begin
The pom.xml will be as follows-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.test</groupId> <artifactId>RestAssuredTest</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-all</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> </dependency> <dependency> <groupId>pl.pragmatists</groupId> <artifactId>JUnitParams</artifactId> <version>1.0.4</version> </dependency> </dependencies> </project>Below we use the Given/When/Then structure that is borrowed from BDD (Behaviour Driven Development). In Given section we declare things like content type or request body. In When section we provide HTTP method and endpoint. In Then section we declare response verification.
package com.javainuse; import org.hamcrest.Matchers; import org.junit.Test; import io.restassured.response.ValidatableResponse; import static io.restassured.RestAssured.given; public class TestRestAssured { @Test public void restAssuredTest() { ValidatableResponse response = given().queryParam("type", "json").when() .get("http://localhost:8080/employee-management-system/viewEmployee/4").then(); System.out.println("Response is - "+response.extract().body().asString()); response.body(Matchers.containsString("emp4")); } }Now start the REST web service we developed in the previous chapter. Run the above class and the test case gets executed successfully. In this test the REST call is made and the response we check if it contains a particular string.
Download Source Code
Download it - Rest-Assured Hello WorldSee Also
REST Project to return XML Response REST Project to return JSON Response