4

Integrate TestNG and Json-Server with Rest-Assured !! - Knoldus Blogs

 3 years ago
source link: https://blog.knoldus.com/integrate-testng-and-json-server-with-rest-assured/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TestNG

TestNG is a testing framework for the Java programming language created by Cédric Beust and inspired by JUnit and NUnit. The design goal of TestNG is to cover a wider range of test categories: unit, functional, end-to-end, integration, etc., with more powerful and easy-to-use functionalities.





Today we’ll cover following topics:

  • A quick intro about Rest Assured?
  • Integration of  TestNG with Rest-Assured
  • What is  JSON Server and how to set it up.
  • How to create or setup a project?

Let’s get to our first question.

What is Rest Assured?

In brief Rest Assured is nothing but a JAVA library or a set of JAVA APIs for testing and validating RESTful webservices.

In other words, REST Assured brings the simplicity of using these languages into the Java domain. Hence you can simply create to test suit using JAVA.

Interestingly it supports both XML and JSON based webservies.

Now, there are lot and lots of functions and classes which we can use to creating a test for a webservices, that I’ll explain you under project setup.

JSON-Server

In short, JSON-Server is basically used to mock the API and provide you access to your data. As a result, we can do data manipulations using rest-assured by using various HTTP method available.

Additionally, Let’s quickly see how we can setup a JSON-Server

1. Firstly, Install JSON Server

npm install -g json-server

    **important to realize: however, make sure you have node.js installed in your computer.

2. After that, create a db.json file with some data like :

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

3. Lastly, open terminal and start JSON Server

Json-server –watch db.json

That’s it!

To conclude, only these were the 3 simple steps to setup and run your JSON server.

let’s move further and setup our first project.

How to create or setup a project and integrate it with TestNG?

slideshow-loader.gif 
In the first place, create a maven project and include the following dependencies in the pom.xml file
<dependencies>
<!-- https://mvnrepository.com/artifact/io.rest-assured/rest-assured -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>com.github.scribejava</groupId>
<artifactId>scribejava-apis</artifactId>
<version>2.5.3</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.1.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.aventstack/extentreports -->
<dependency>
<groupId>com.aventstack</groupId>
<artifactId>extentreports</artifactId>
<version>4.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-schema-validator -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.rest-assured/json-path -->
<depeneency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>4.1.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.rest-assured/xml-path -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>4.1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>java-hamcrest</artifactId>
<version>2.0.0.0</version>
<scope>test</scope>
</dependency>
</dependencies>

by the time, you’re all set to start framing our Test class

In order to do the same, just follow the steps as shown below

1. Firstly, class variable for rest assured and extent report classes

static RequestSpecification request;
static int status_code;
static String id = "44";
static ExtentTest logger;
static ExtentReports extent = new ExtentReports();

2. After that, we’ll setup our Extent report and write the code for initializing your ExtentReport under @BeforeClass annotation(TestNG) so that this method can run at the very beginning.

      @BeforeClass
	public void reportsInitialization() {
	ExtentHtmlReporter reporter = new ExtentHtmlReporter("./Reports/AllRequest_Extent_Report.html");
		
		// Environment Setup
		extent.setSystemInfo("OS Name", "Windows");
		extent.setSystemInfo("Username", "Aman Saxena");
		extent.attachReporter(reporter);
//Provide the title and description of you test
		logger = extent.createTest("***API Test***", "All API methods will be tested here");
	}

important to realize: Wherever you need log any information in your extent report, use methods like, logger.pass(“message”), logger.fail(“message”), logger.warning(“message”), etc.

  1. Next, create a method under @AfterClass annotation (TestNG) to flush/export your extent report at the end of your test
 @AfterClass
	public void reports() {
		extent.flush();

So, Above all, are the step by which, we’re all set to write our first test for validating our RESTful API

Now move to the steps to write the test case

1. For instance write a test case for POST call

For instance, there are two types of payloads/method bodies which we can use under the post method:

a. Simple payload

b. Complex payloads

Firstly, let’s discuss both of them but start with the simple one

a. Simple Payload : In short, these are the object written in simple key/value pairs without having any nested array and something like that.

for example:


		// create a json object
		JSONObject jobj = new JSONObject();
		jobj.put("id", 14);
		jobj.put("title", "RestAssured");
		jobj.put("author", "Test User");
		// parse the json object into the request body
		request.body(jobj.toJSONString());
		==========================================
		// Json string generated here will be like 
                {"id" : "14",
                 "title" : "RestAssured", 
                 "author" : "Test User"   
                 }

b. Complex Payload : These are the object having nested objects or array of objects. For creating complex payload we can use POJO classes. like below and if you don’t know about those then I recommend you to learn about that first from https://www.geeksforgeeks.org/pojo-vs-java-beans/

another key point, just create the following POJO classes in your project.
Ad Class:
public class Ad { 
String company;
String url;
String text;
public Ad(String company, String url, String text) {
this.company=company;
this.url=url;
this.text=text;
} public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
} }
Data Class:
package utils; 
public class Data {
String email;
String first_name;
String last_name;
String avatar;
public Data( String email, String first_name, String last_name, String avatar) {
this.email = email;
this.first_name = first_name;
this.last_name = last_name;
this.avatar = avatar;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
} }
PatchPayload Class:
package utils; 
public class PatchPayload {
String id;
String email;
String password;
Data data;
Ad ad;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}

public Ad getAd() {
return ad;
}
public void setAd(Ad ad) {
this.ad = ad;
}
public PatchPayload(String id,String email, String password, Data data, Ad ad) {
this.id = id;
this.data = data;
this.ad = ad;
this.email=email;
this.password=password;
} }
SendPayload Class:
package utils; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class SendPayload {
static String finalPayload;
public SendPayload(String id, String email, String password, String first_name, String last_name, String avatar, String company, String url, String text) {
if (text.isEmpty()) {
text = "Here we can provide text description what ever we want";
}
Data d = new Data(email, first_name, last_name, avatar);
Ad a = new Ad(company, url, text);
PatchPayload p = new PatchPayload(id, email, password, d, a);
ObjectMapper o = new ObjectMapper();
try {
finalPayload = o.writerWithDefaultPrettyPrinter().writeValueAsString(p);
} catch (JsonProcessingException e) { e.printStackTrace();
}
System.out.println(finalPayload);
} }

2. Additionally, create an anonymous object of SendPayload class and provide the required details like I’ve provided as arguments.

new SendPayload(id, "testuser.com","abc@123", "Test", "User", "avatar.jpg", 
                "ABC pvt ltd", "https://mywebsite.com", "");

3. After that, use the finalPayload method of SendPayload class to get the generate payload and parse that to body of you request like :

 request.body(SendPayload.finalPayload);

5. At this point, execute your call and catch it’s status code in any variable

status_code = request.post().thenReturn().getStatusCode();
		if (status_code == 201) {
		logger.pass("Data successfully posted to the server");	
		} 
                else {
			fail();
	                logger.fail("Failed post request");
		     }
    	}

in the same way, create other request like put, delete, get using respective keywords like below:

@Test(priority = 2) public void putData() { 
new SendPayload(id, null,"abc@123", null, "User", "profile.jpg", "ABC pvt ltd", "https://specialwebsite.com", ""); request.body(SendPayload.finalPayload);
status_code = request.put().getStatusCode();
if (status_code == 200) {
logger.pass("Data successfully updated in the database");
} else {
fail();
logger.fail("Failed post request");
} }
@Test(priority = 3) public void patch() { 
new SendPayload(id, "","abc@123", "", "", "patch.jpg", "ABC pvt ltd", "https://patchwebsite.com", "");
request.body(SendPayload.finalPayload);
status_code = request.patch().getStatusCode();
if (status_code == 200) {
Assert.assertEquals(200, status_code);
logger.pass("Data successfully patched in the database");
} else {
fail();
logger.fail("Failed post request");
} }
@Test(priority = 4) public void delete() { 
status_code = request.delete().getStatusCode();
if (status_code == 200) {
Assert.assertEquals(200, status_code);
logger.pass("Data successfully patched in the database");
} else {
fail();
logger.fail("Failed post request");
}
In addition, create a method under @AfterMethod annotation as a finishing step for every test case and define get method so that after every other call that we will execute which will manipulate the data, we can print the changes :
@AfterMethod
	public void testCompletion() {

		//To print the reponse after every http call
		request.get().body().prettyPrint();
		//resetting the variables
		request = null;
		status_code = 0;
		request = RestAssured.given().baseUri("http://localhost:3000/posts/" + id).contentType(ContentType.JSON);

	}
Finally, Execute the class as TestNG Test by clicking anywhere Run As>> TestNG Test

Therefore, You will see that all the test cases will pass and in the terminal where json server is running. So, there will be a log of all the calls hitting the server.

In addition to above, check for the Extent Report at the path you have provided and open it in your browser. Hence, It will look something like this.

slideshow-loader.gif 

So, to conclude that’s all for this topic . Above all, are the simple steps by which you can create and automate your first API test

Unquestionably, you can use below mentioned reference for further information

what’s more:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK