REST Assured Framework is a JAVA DSL(Domain Specific Language) for simplifying testing of REST APIs. It eliminates the need to write boiler plate code to invoke REST APIs and to validate complex responses. It supports both JSON and XML request/responses.
Let's see how to create automated tests using Java, Maven, Eclipse and REST Assured.
I assume that you have Java JDK, maven and Eclipse installed in your system.
Steps:
1. Open Eclipse.
2. Create a new Maven Project.
3. Open pom.xml in Eclipse.Add the following dependency in pom.xml:
com.jayway.restassured
rest-assured
2.5.0
test
Let's see how to create automated tests using Java, Maven, Eclipse and REST Assured.
I assume that you have Java JDK, maven and Eclipse installed in your system.
Steps:
1. Open Eclipse.
2. Create a new Maven Project.
3. Open pom.xml in Eclipse.Add the following dependency in pom.xml:
Also add testNG dependency in pom.xml
4. Select Project name in Project Explorer panel. Right click ->maven->Update Project...
This step will download the appropriate jar files from Maven repository through online. Make sure you have internet connection enabled. And also build the project.
5. Create a testng java class (class name should have suffix *Test) under src/test/java/ package:
SampleTest.java
import static com.jayway.restassured.RestAssured.expect;
import static com.jayway.restassured.RestAssured.given;
import static com.jayway.restassured.RestAssured.post;
import static org.hamcrest.Matchers.equalTo;
import org.testng.annotations.Test;
import com.jayway.restassured.path.json.JsonPath;
import com.jayway.restassured.response.Response;
public class SampleTest {
@Test()
public void testSample(){
expect().
statusCode(200).
body("token_type", equalTo("Token")).
when().
post("https://sampleRESTAPIurl?id=100");
Response res = post("https://sampleRESTAPIurl?id=100");
String json = res.asString();
System.out.println(json);
JsonPath jp = new JsonPath(json);
String token = jp.get("access_token");
System.out.println (jp.get("access_token"));
Response re = given().
header("Authorization"," "+token.trim()).when().
get("https://sampleRestAPI/url?loggedId=venkat");
System.out.println(re.asString());
}
}
6. Select the project ->Rightclick->RunAs->maven test
This step will run the SampleTest.java and show the results in Console.
Anatomy of the SampleTest.java:
Do Static imports of expect,given,post methods from the respective java class. Also import JsonPath and Response java classes. Then write the test cases in Given-When-Then format.