JUnit is an open source Unit Testing Framework for JAVA. JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks.
For the successful execution of Agile testing requirements, a perfect test automation tool is required. And there are numerous factors to consider when creating a solid automation framework. One such component is reporting, which not only informs you of the success or failure of the project but also assists you in identifying potential bugs. JUnit is another useful framework that can add the ability to generate reports in Selenium. This tutorial explains the steps to generate the JUnit5 Report.
The PATCH method is used to partially modify an existing resource. This operation updates an existing resource but does not require sending the entire body with the request. PUT modifies a record’s information and creates a new record if one is not available, and PATCH updates a resource without sending the entire body of the request. Unlike PUT Request, PATCH does partial update e.g. Fields that need to be updated by the client, only that field is updated without modifying the other field.
We will use the following URL for this Postman tutorial.
https://reqres.in/api/users/2
Sample Request Body
{
"name": "Patch_Test"
}
Implementation Steps:
To create the first PATCH request in Postman, follow the following steps:
Create a Collection
Step 1: Create a Collection, click on Collections, and then click on the “+” plus button.
Step 2: Provide a name to the collection – “API Testing”.
Add a request to the Collection
Step 3: To create a new request, click on “Add a request” if it is a new Collection. Otherwise, click on the 3 dots and select “Add request”.
Step 4: Once you create a new request, then you will get the following window:
Enter the details of request
Step 5: Enter the “name” in the request. Here, the name is “PartiallyUpdateUser”.
Step 6:Enter the “URL” in the address bar.
Step 7:Now, select the “PATCH” request from the list of request methods.
Step 8: Add a Request body to the Post request
For this, select the Body tab.
Now in the Body tab, select raw and select JSON as the format type from the drop-down menu, as shown in the image below. This is done because we need to send the request in the appropriate format that the server expects. Copy and paste the request body example mentioned at the beginning of the tutorial to the postman request Body.
Step 9: Press the “Send” button.
Verify the Response
Step 10: Once you press the send button, you will get the response from the server. Make sure you have a proper internet connection; otherwise, you will not get a response.
Status
You can check the status code. Here, we got the status code 200, which means we got a successful response to the request. In the case of new resource creation, the status code should be 201. But as this is a dummy API, we are getting a status code of 200.
Body
In the Body tab of the response box, we have multiple options to see the response in a different format.
Format Type
Each request has a defined response to it as defined by the Content-Type header. That response can be in any format. Such as in the above example, we have JSON code file.
Below are the various format type present in Postman.
XML
HTML
Text
Headers
Headers are the extra information that is transferred to the server or the client. In Postman, headers will show like key-value pairs under the headers tab. Click on the Headers link as shown in the below image:
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Step 1.1 – Open PyCharm and create a new project. Go to File and select New Project from the main menu.
Step 1.2 – Choose the project location. Click the “Browse” button next to the Location field and specify the directory for your project.
Deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.
Click on the “Create” Button.
Step 1.3 – A new dialog appears asking to open the project using any one of the given options. I have selected New Window as I like to have separate windows for each project.
Below is the image of the new project created in PyCharms.
Step 2 – Create a new directory in the new project
Right-Click on the project, select New->Directory and provide name as Tests
Below is the image of the new directory.
Right-click on the new directory and select New File and provide the name as HeadlessChrome_Demo.robot and Headlessas shown below:
Step 3 – Execute tests in headless mode
We are now going to write test cases. The test case details will be as follows −
Below is an example of executing Chrome tests in headless mode.
*** Settings ***
Documentation To validate the Login Form
Library SeleniumLibrary
*** Test Cases ***
Validate Unsuccessful Login
Open the Browser with URL
Fill the login form
verify error message is correct
*** Keywords ***
Open the Browser with URL
Open Browser https://opensource-demo.orangehrmlive.com/web/index.php/auth/login headlesschrome
Maximize Browser Window
Set Selenium Implicit Wait 5
Fill the login form
Input Text css:input[name=username] Admin
Input Password css:input[name=password] Admin
Click Button css:.orangehrm-login-button
verify error message is correct
${result}= Get Text CSS:.oxd-alert-content-text
Should Be Equal As Strings ${result} Invalid credentials
Below is an example of executing Firefox tests in headless mode.
*** Settings ***
Documentation To validate the Login Form
Library SeleniumLibrary
*** Test Cases ***
Validate Unsuccessful Login
Open the Browser with URL
Fill the login form
verify error message is correct
*** Keywords ***
Open the Browser with URL
Open Browser https://opensource-demo.orangehrmlive.com/web/index.php/auth/login headlessfirefox
Maximize Browser Window
Set Selenium Implicit Wait 5
Fill the login form
Input Text css:input[name=username] Admin
Input Password css:input[name=password] Admin
Click Button css:.orangehrm-login-button
verify error message is correct
${result}= Get Text CSS:.oxd-alert-content-text
Should Be Equal As Strings ${result} Invalid credentials
All the below-mentioned keywords are derived from SeleniumLibrary except the last one. The functionality of keywords mentioned above:
1. Open Browser − The keyword opens a new browser instance to the optional URL.
2. Maximize Browser Window – This keyword maximizes the current browser window.
3. Set Selenium Implicit Wait – This keyword sets the implicit wait value used by Selenium.
4. Input Text − This keyword is used to type the given text in the specified textbox identified by the locator name:username.
5. Input Password – This keyword is used to type the given text in the specified password identified by the locator name:password.
The difference compared to Input Text is that this keyword does not log the given password on the INFO level.
6. Click button – This keyword is used to click on the button with location css:.orangehrm-login-button.
7. ${result} – This is a variable that holds the text value of the error message that is located by css:.oxd-alert-content-text
8. Get Text – This keyword returns the text value of the element identified by located by css:.oxd-alert-content-text.
9. Should Be Equal As Strings – This keyword is used from builtIn keyword. This keyword returns false if objects are unequal after converting them to strings.
To run this script, go to the command line and go to directory tests.
Step 4 – Execute the tests
We need the below command to run the Robot Framework script.
robot .
The output of the above program is
Step 5 – View Report and Log
We have the test case passed. The Robot Framework generates log.html, output.xml, and report.html by default.
Let us now see the report and log details.
Report
Right-click on report.html. Select Open In->Browser->Chrome(any browser of your wish).
The Report generated by the framework is shown below:
Log
Robot Framework has multiple log levels that control what is shown in the automatically generated log file. The default Robot Framework log level is INFO.
Right-click on log.html. Select Open In->Browser->Chrome(any browser of your wish).
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Step 1.1 – Open PyCharm and create a new project. Go to File and select New Project from the main menu.
Step 1.2 – Choose the project location. Click the “Browse” button next to the Location field and specify the directory for your project.
Deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.
Click on the “Create” Button.
Step 1.3 – A new dialog appears asking to open the project using any one of the given options. I have selected New Window as I like to have separate windows for each project.
Below is the image of the new project created in PyCharms.
Step 2 – Create a new directory in the new project
Right-Click on the project, select New->Directory, and provide the name as Tests
Below is the image of the new directory.
Right-click on the new directory, select New File and provide the name as Drag_And_Drop_Demo.robot as shown below:
Step 3 – Download ChromeBinaries from the below location
The tests are going to use the Chrome browser, so we need to download the ChromeBinaries to open a blank browser in Chrome.
The chromedriver and geckodriver are placed in a folder named drivers in the RobotFramework_Demo project. I have renamed chromedriver to Chrome and geckodriver to Firefox.
Step 4 – Automate the drag and drop option
We are now going to write test cases. The test case details will be as follows −
Open the Browser with the URL
Verify element Text before drag
Drag the element and drop
Verify element Text after drag
To work with the Radio Button, we need a locator. A locator is an identifier for the textbox like id, name, class, xpath, css selector, etc.
To know more about locators, refer to these Selenium Tutorials:
Let us inspect the locator of the drag and drop option.
Below is an example of a drag and drop option.
*** Settings ***
Documentation To drag the box
Library SeleniumLibrary
*** Test Cases ***
Verify that the user can drag and drop elements
[documentation] This test case verifies that a user can drag and drop an element from source to destination
Open the Browser with URL
Verify element Text before drag
Drag the element and drop
Verify element Text after drag
*** Keywords ***
Open the Browser with URL
Create Webdriver Chrome executable_path=/Vibha_Personal/RobotFramework_Demo/drivers/Chrome
Go To https://demoqa.com/droppable
Maximize Browser Window
Set Selenium Implicit Wait 5
Verify element Text before drag
Element Text Should Be id:droppable Drop here timeout=5 #Before Drag and Drop
Drag the element and drop
Drag And Drop id:draggable id:droppable
Verify element Text after drag
Element Text Should Be id:droppable Dropped! timeout=5 #After Drag and Drop
All the below-mentioned keywords are derived from SeleniumLibrary except the last one. The functionality of keywords mentioned above:
1. Create Webdriver − The keyword creates an instance of Selenium WebDriver.
2. Go To – This keyword navigates the current browser window to the provided URL – https://demoqa.com/droppable.
3. Maximize Browser Window – This keyword maximizes the current browser window.
4. Set Selenium Implicit Wait – This keyword sets the implicit wait value used by Selenium.
5. Element Text Should Be – This keyword is used to verify that the current page contains the exact text identified by the locator.
6. Drag And Drop – Drags the element identified by the locator into the target element. The locator argument is the locator of the dragged element and the target is the locator of the target.
7. Drag And Drop By Offset – Drags the element identified with locator by xoffset/yoffset. The element will be moved by xoffset and yoffset, each of which is a negative or positive number specifying the offset.
Step 5 – Automate the Drag and Drop by Offset option
Drag And Drop By Offset – Drags the element identified with the locator by xoffset/yoffset.
*** Settings ***
Documentation To drag the box
Library SeleniumLibrary
Test Teardown Close Browser
*** Test Cases ***
Verify that the user can drag and drop element by offset
[documentation] This test case verifies that a user can drag and drop an element by offset
Open the Browser with URL
Verify element Text before drag
Drag the element and drop locator by xoffset/yoffset
Verify no change in Text
*** Keywords ***
Open the Browser with URL
Create Webdriver Chrome executable_path=/Vibha_Personal/RobotFramework_Demo/drivers/Chrome
Go To https://demoqa.com/droppable
Maximize Browser Window
Set Selenium Implicit Wait 5
Verify element Text before drag
Element Text Should Be id:droppable Drop here timeout=5 #Before Drag and Drop
Drag the element and drop locator by xoffset/yoffset
Drag And Drop By Offset id:draggable 50 70
Verify no change in Text
Element Text Should Be id:droppable Drop here timeout=5 #After Drag and Drop
Before
After
Step 6 – Execute the tests
We need the below command to run the Robot Framework script.
robot Drag_Drop_Demo.robot
The output of the above program is
Step 7 – View Report and Log
We have the test case passed. The Robot Framework generates log.html, output.xml, and report.html by default.
Let us now see the report and log details.
Report
Right-click on report.html. Select Open In->Browser->Chrome (any browser of your wish).
The Report generated by the framework is shown below:
Log
Robot Framework has multiple log levels that control what is shown in the automatically generated log file. The default Robot Framework log level is INFO.
Right-click on log.html. Select Open In->Browser->Chrome (any browser of your wish).
That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
Jenkin’s installed and started on the computer. The current Jenkins version is – 2.361.2
Implementation Steps
To generate HTML Report in Jenkins, we need to download HTML Publisher Plugin. Please refer to this tutorial to install the plugin – How to install Plugins in Jenkins.
Step 1: Create a new Maven project
Give the Name of the project – HTMLReport_Demo
Click on the Maven project.
Click on the OK button.
In the General section, enter the project description in the Description box.
Select Source Code Management as None if the project is locally present on the machine.
Step 2: Build Management
Go to the Build section of the new job.
In the Root POM textbox, enter the full path to pom.xml
In the Goals and Options section, enter “clean test site“
Here, I have used the Selenium project with JUnit, so to see the complete project, please refer to this tutorial – How to generate JUnit4 Report.
Click on the Advanced button.
Step 3: Select a custom workspace
Mention the full path of the project in the directory.
Step 4: Select “Publish HTML reports” from “Post Build Actions”
Scroll down to “Post Build Actions” and click on the “Add Post Build Actions” drop-down list. Select “Publish HTML reports“.
If you want to see where the report is saved in Jenkins, go to the Dashboard ->HTMLReport_Demo project -> Workspace ->target -> site -> surefire-report.html.
Enter the below details to publish HTML reports
HTML directory to archive – target/site/
Index page[s] – surefire-report.html
Report title – HTML Report
Click on the Apply and Save buttons.
We have created a new Maven project “HTMLReport_Demo” with the configuration to run the Selenium with JUnit4 Tests and also to generate HTML Report after execution using Jenkins.
Step 5: Execute the tests
Let’s execute it now by clicking on the “Build Now” button.
Right-click on Build Number (here in my case it is #2).
Click on Console Output to see the result.
Step 6: View the HTML Report
Once the execution is completed, click on go “Back to Project“, and we can see a link to view the “HTML Report“.
We can see here that the HTML Report link is displayed in the Console.
Below is the HTML Report generated in Jenkins.
We can see that the HTML Report does not look very pretty. The reason is that CSS is stripped out because of the Content Security Policy in Jenkins.
We can customize the Content Security Policy in Jenkins. But keep in mind that it should be done after checking with the Security team in your organization. This is a workaround solution. I can’t emphasize enough that this is not a standard practice.
Go to Manage Jenkins -> Manage Nodes and Clouds.
Click on the Script Console option.
Type in the following command and Press Run. If you see the output as ‘Result:’ then the protection is disabled. Re-run your build and you can see that the new HTML files archived will have the CSS enabled.
In the previous tutorial, I explained the Integration of the Allure Report with Rest Assured with JUnit4. In this tutorial, I will explain how to Integrate Allure Report with Rest Assured and TestNG.
The below example covers the implementation of Allure Report for Rest API using Rest Assured, TestNG, Java, and Maven.
Step 4 – Create the Test Code for the testing of REST API under src/test/java
To see our request and response in more detail using Rest Assured, we need to add a line to our Rest Assured tests. This will provide the request and response details in the report.
.filter(new AllureRestAssured())
import io.qameta.allure.*;
import io.qameta.allure.restassured.AllureRestAssured;
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@Epic("REST API Regression Testing using TestNG")
@Feature("Verify CRUID Operations on User module")
public class RestAPITests {
@Test(description = "To get the details of user with id 3", priority = 0)
@Story("GET Request with Valid User")
@Severity(SeverityLevel.NORMAL)
@Description("Test Description : Verify the details of user of id-3")
public void verifyUser() {
// Given
given()
.filter(new AllureRestAssured())
// When
.when()
.get("https://reqres.in/api/users/3")
// Then
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
// To verify user of id 3
.body("data.email", equalTo("emma.wong@reqres.in"))
.body("data.first_name", equalTo("Emma"))
.body("data.last_name", equalTo("Wong"));
}
@Test(description = "To create a new user", priority = 1)
@Story("POST Request")
@Severity(SeverityLevel.NORMAL)
@Description("Test Description : Verify the creation of a new user")
public void createUser() {
JSONObject data = new JSONObject();
data.put("name", "RestAPITest");
data.put("job", "Testing");
// GIVEN
given()
.filter(new AllureRestAssured())
.contentType(ContentType.JSON)
.body(data.toString())
// WHEN
.when()
.post("https://reqres.in/api/users")
// THEN
.then()
.statusCode(201)
.body("name", equalTo("RestAPITest"))
.body("job", equalTo("Testing"));
}
}
Step 5 – Create testng.xml for the project
<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
<test name = "TestNG Test Demo">
<classes>
<class name = "org.example.RestAPITests"/>
</classes>
</test>
</suite>
Step 6 – Run the Test and Generate Allure Report
To run the tests, use the below command
mvn clean test
In the below image, we can see that all three tests are passed.
This will create the allure-results folder with all the test reports. These files will be used to generate the Allure Report.
To create an Allure Report, use the below command
allure serve
This will generate the beautiful Allure Test Report as shown below.
Allure Report Dashboard
The overview page hosts several default widgets representing the basic characteristics of your project and test environment.
Categories in Allure Report
The categories tab gives you a way to create custom defect classifications to apply for test results. There are two categories of defects – Product Defects (failed tests) and Test Defects (broken tests).
Suites in Allure Report
On the Suites tab a standard structural representation of executed tests, grouped by suites and classes, can be found.
View test history
Each time you run the report from the command line with the mvn clean test command, a new result JSON file will get added to the allure-results folder. Allure can use those files to include a historical view of your tests. Let’s give that a try.
To get started, run mvn clean test a few times and watch how the number of files in the allure-reports folder grows.
Now go back to view your report. Select Suites from the left nav, select one of your tests and click Retries in the right pane. You should see the history of test runs for that test:
Graphs in Allure Report
Graphs allow you to see different statistics collected from the test data: status breakdown or severity and duration diagrams.
Timeline in Allure Report
Timeline tab visualizes retrospective of tests execution, allure adaptors collect precise timings of tests, and here on this tab, they are arranged accordingly to their sequential or parallel timing structure.
Behaviors of Allure Report
This tab groups test results according to Epic, Feature, and Story tags.
Packages in Allure Report
The packages tab represents a tree-like layout of test results, grouped by different packages.
We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!
As we know, REST Assured is a Java DSL for simplifying the testing of REST-based services built on top of HTTP Builder. In this tutorial, I’ll create a Test Framework for the testing of REST API using REST Assured and TestNG as the test framework.
Java needs to be present on the system to run the tests. Click here to know How to install Java. To know if Java is installed or not on your machine, type this command in the command line. This command will show the version of Java installed on your machine.
java -version
Step 2 – Download and setup Eclipse IDE on the system
The Eclipse IDE (integrated development environment) provides strong support for Java developers, which is needed to write Java code. Click here to know How to install Eclipse.
Step 3 – Setup Maven
To build a test framework, we need to add a number of dependencies to the project. It is a very tedious and cumbersome process to add each dependency manually. So, to overcome this problem, we use a build management tool. Maven is a build management tool that is used to define project structure, dependencies, build, and test management. Click here to know How to install Maven.
To know if Maven is already installed or not on your machine, type this command in the command line. This command will show the version of Maven installed on your machine.
To know more about priority in TestNG, please refer tothis tutorial.
import io.restassured.http.ContentType;
import org.json.JSONObject;
import org.testng.annotations.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class RestAPITests {
@Test(description = "To get the details of user with id 3", priority = 0)
public void verifyUser() {
// Given
given()
// When
.when()
.get("https://reqres.in/api/users/3")
// Then
.then()
.statusCode(200)
.statusLine("HTTP/1.1 200 OK")
// To verify user of id 3
.body("data.email", equalTo("emma.wong@reqres.in"))
.body("data.first_name", equalTo("Emma"))
.body("data.last_name", equalTo("Wong"));
}
@Test(description = "To create a new user", priority = 1)
public void createUser() {
JSONObject data = new JSONObject();
data.put("name", "RestAPITest");
data.put("job", "Testing");
// GIVEN
given()
.contentType(ContentType.JSON)
.body(data.toString())
// WHEN
.when()
.post("https://reqres.in/api/users")
// THEN
.then()
.statusCode(201)
.body("name", equalTo("RestAPITest"))
.body("job", equalTo("Testing"));
}
}
Step 7 – Test Execution through TestNG
Go to the Runner class and right-click Run As TestNG Test. The tests will run as TestNG tests. (Eclipse)
Right-click on the test page and select Run ‘RestAPITests’ in thecase of Intellij.
This is how the execution console will look like. (IntelliJ)
Eclipse
Step 8 – Run the tests from TestNG.xml
Create a TestNG.xml as shown below and run the tests as TestNG. Here, the tests are present in class – com.example. Selenium_TestNGDemo.API_Test.
<?xml version = "1.0"encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite1">
<test name = "TestNG Test Demo">
<classes>
<class name = "org.example.RestAPITests"/>
</classes>
</test>
</suite>
Step 9 – TestNG Report Generation
After the test execution, refresh the project, and a new folder with the name test-output will be generated. This folder contains the reports generated by TestNG. The structure of folder test-output looks as shown below.
Emailable-report.html
We are interested in “emailable-report.html” report. Open “emailable-report.html”, as this is an HTML report, open it with the browser. The below image shows emailable-report.html.
Index.html
TestNG also produces “index.html” report, and it resides under the test-output folder. The below image shows the index.html report. This report contains a high-level summary of the tests.
JSONArrayrepresents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.
JSON array can store multiple value types. The values in a JSONArray can be of the following types: JsonObject, JsonArray, JsonString, JsonNumber, JsonValue.TRUE, JsonValue.FALSE, and JsonValue.NULL.
The array index begins with 0.
The square brackets [ ] are used to declare the JSON array.
An API can accept a JSON Array payload as a request body. Imagine, we want to add employee details of more than one employee in the below example. In this case, we can pass multiple JSON objects within a JSON array. I have explained 2 ways to create JSON Object – map or JsonObject. Refer to any one of the tutorials to get to know about the creation of JSON Object.
To create a JSON Array, we need to add org.jsonMaven dependency, as shown below. The latest version can be found here.
Create a JSON Object and add the first employee details.
Create another JSON Object and add second guest details.
Create a JSONArray.
Add both JSON Objects to JSONArray.
Below is an example of creating a request from JSONArray with multiple JSON Objects. I am using a logger just to print the JSON body in the Console.
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
public class Json_Demo {
@Test
public void passBodyAsJsonArrayDemo() {
// JSON Object for first employee
JSONObject data1 = new JSONObject();
data1.put("employee_name", "ObjectTest");
data1.put("profile_image", "test1.png");
data1.put("employee_age", "30");
data1.put("employee_salary", "11111");
// JSON Object for second employee
JSONObject data2 = new JSONObject();
data2.put("employee_name", "MapTest");
data2.put("profile_image", "test2.png");
data2.put("employee_age", "20");
data2.put("employee_salary", "99999");
// Creating JSON array to add both JSON objects
JSONArray array = new JSONArray();
array.put(data1);
array.put(data2);
// Send the request
RestAssured.given()
.contentType(ContentType.JSON)
.body(array.toString())
.log().all()
.when()
.post("https://dummy.restapiexample.com/api/v1/create")
.then()
.assertThat().statusCode(200)
.body("message", equalTo("Successfully! Record has been added."))
.log().all();
}
}
The output of the above program is
Explanation:
1. Creating JSON Objects:
Two “JSONObject” instances (‘data1‘ and ‘data2‘) are created to represent two employees. Each JSON object contains employee details such as name, profile image, age, and salary.
// JSON Object for first employee
JSONObject data1 = new JSONObject();
data1.put("employee_name", "ObjectTest");
data1.put("profile_image", "test1.png");
data1.put("employee_age", "30");
data1.put("employee_salary", "11111");
// JSON Object for second employee
JSONObject data2 = new JSONObject();
data2.put("employee_name", "MapTest");
data2.put("profile_image", "test2.png");
data2.put("employee_age", "20");
data2.put("employee_salary", "99999");
2. Creating a JSON Array:
A JSONArrayinstance is created, and both JSON objects (data1 and data2) are added to it.
JSONArray array = new JSONArray();
array.put(data1);
array.put(data2);
3. Sending the POST Request:
3.1 The RestAssured library constructs and sends the HTTP POST request. It sets the content type of the request to JSON.
contentType(ContentType.JSON)
3.2 Converts the JSON array into a string format and sets it as the body of the request.
.body(array.toString())
3.3 Logs all details of the request for debugging purposes.
4.2 Asserts that the response status code is 200, indicating a successful request.
.assertThat().statusCode(200)
4.3 Asserts that the body of the response contains the specified message, confirming successful addition of records.
.body("message", equalTo("Successfully! Record has been added."))
4.4 Logs all details of the response for debugging purposes.
.log().all()
Complex JSON Array
Let us see an example of a complex JSON Array. This structure represents two separate employee data sets. Each is contained within its own JSON array. The whole is encapsulated within a larger JSON object identified by keys employee1and employee2.
Two JSONArray instances (array1 and array2) are created to encapsulate each employee’s JSON object.
JSONArray array1 = new JSONArray();
array1.put(data1);
JSONArray array2 = new JSONArray();
array2.put(data2);
3. Composing The JSON Structure:
A third JSONObject, data3, is created to aggregate the two JSON arrays under separate keys: employee1 and employee2.
JSONObject data3 = new JSONObject();
data3.put("employee1", array1);
data3.put("employee2", array2);
4. Output the JSON Object:
The entire composite JSON structure (data3) is printed to the console. The toString(4) method formats the output with an indentation of 4 spaces for readability.
System.out.println(data3.toString(4));
Similarly, there is another way to create this JSON Structure.
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
public class Json_Demo {
@Test
public void passBodyAsJsonArray1() {
// Creating JSON array to add first JSON object
JSONArray array1 = new JSONArray();
array1.put(new JSONObject().put("firstname", "Tom").put("lastname", "Mathew").put("age", 59).put("salary",
720000));
// Creating JSON array
JSONArray array2 = new JSONArray();
array2.put(new JSONObject().put("firstname", "Perry").put("lastname", "David").put("age", 32).put("salary",
365000));
// Create JSON Object to add JSONArrays
JSONObject data1 = new JSONObject();
data1.put("employee1", array1);
data1.put("employee2", array2);
System.out.println(data1.toString(4));
}
}
The output of the above program is
Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!
Authorization with a dynamic access token is used to pass dynamic response content to subsequent requests. This is used to validate API authorization.
In this post, we will discuss fetching an access token (dynamic response) with the help of JSON Extractor. We will also show how to pass it as a parameter in the subsequent request using BeanShell Assertion.
To achieve authorization with access token, we need to create 2 Thread Groups:
Thread Group 1 – To generate Access Token Thread Group 2 – To pass Access Token to Request
Prerequisite:
Install JMeter on your system.
Implementation Steps:
Step 1 – Add Thread Group 1: Thread Group – Authorization Token Generation
1. Add Thread Group
We should provide the name of the Thread Group. In this case, this thread group is used to generate the token, so named Token Generation. We want to generate only 1 token, so the Number of Threads, Ramp-up period, and Loop Count are 1 only.
2. Add HTTP Request Sampler
In the HTTP Request Control Panel, the Path field indicates which URL request you want to send
To add:Right-clickon Thread Group and select: Add -> Sampler -> HTTP Request
Add valid credentials in the parameters section.
3. Add HTTP Header Manager
The Header Manager lets you add or override HTTP request headers like can add Accept-Encoding, Accept, Cache-Control
To add: Right-click on Thread Group and select: Add -> Config Element -> HTTP Read Manager
Add Authorization as Headers in Header Manager
4. Add JSON Extractor
To extract the authentication token from the request, we are going to use JMeter JSON Extractor. The process of extracting a variable from a response works as mentioned below:
First, the server sends back a response. Then a post-processor, like the JSON Extractor, executes. It extracts part of the response and puts it into a variable like ${token}.
To add:Right-click on Thread Group and select: Add -> Post Processors -> JSON Extractor
The JSON extractor requires us to follow a few steps, so we can process the JSON correctly.
1) Name – JSON Extractor 2) Apply to – we will use the defaulted Main Sample Only. The option is: The main sample only – the assertion only applies to the main sample 3)Name of created variables– BEARER 4) JSON Path Expressions – access_token
5. Add BeanShell Assertion
An advanced assertion with full access to JMeter API. Java conditional logic can be used to set the assertion result.
To add:Right-click on Thread Group and select: Add -> Assertions -> BeanShell Assertions
Add the below-mentioned script in the Script section of BeanShell Assertion
${__setProperty(BEARER, ${BEARER})};
Step 2 – Add Thread Group 2: Thread Group – Main Request
1. Add Thread Group
Provide a name to this Thread Group. I have also provided the number of threads, ramp-up, and duration in the thread group as shown in the image
We can parameterize the values of the number of threads. We can also do this for the ramp-up period and duration. This is done using a JMeter property called ___P. You can ask why we are using the property function in JMeter. It is because this makes the JMeter script configurable. We can pass any value through the command line without making any changes in the script.
___P – This is a simplified property function that is intended for use with properties defined on the command line.
If no default value is supplied, it is assumed to be 1. The value of 1 was chosen because it is valid for common test variables such as loops, thread count, ramp-up, etc.
${__P(group1.threads)} – return the value of group1.threads
${__P(THREADS,1)} – This THREADS value will be passed through command line. If no value is passed, by default, it will choose 1.
Similarly, ramp-up and duration are parameterized.
Below-mentioned are the values used in HTTP Request to perform the test
Add a valid request body in the Body Data section (if the request is POST).
3. Add HTTP Header Manager
We have previously extracted the token from the Token Generation request. Now, it’s time to reuse it in the header section of HTTP Header Manager.
Below are the values used in the HTTP Request to perform the test.
Authorization = Bearer ${__property(BEARER)}
Step 3 – Adding Listeners to the Test Plan
Listeners – They show the results of the test execution. They can show results in a different format such as a tree, table, graph, or log file
We have added listeners – View Result Tree
View Result Tree – View Result Tree shows the results of the user request in basic HTML format
To add: Right-click Test Plan, Add -> Listener -> View Result Tree
Step 4 – Save the Test Plan
To Save: Click FileSelect -> Save Test Plan as ->Give the name of the Test Plan. It will be saved as .jmx format.
Step 5 – Run the Test Plan
Click on Green Triangle as shown at the top to run the test.
Step 6 – View the Execution Status
Click on View Result Tree to see the status of Run. A successful request will be of a Green colour in the Text Section
Here, we can see that the Token Generation request is successfully processed.
The below image shows that the Main Request is successfully executed too.
Troubleshooting
Correct Authorization Setup
In JMeter, typically, we will use an HTTP Header Manager to include your access token in requests. Make sure the token is formatted correctly: `Authorization: Bearer `.
Understand the Authorization Type
Make sure correct type of authorization is required (e.g., Bearer Token) and how the access token should be included in requests (usually in the headers).
Network and Endpoint Checks
Check for firewall rules or network issues that might be blocking access.
Congratulation!! We can add an authorization token generated by a request add it to another request and process the request using JMeter.