Postman Tutorial for Automation : All you need to know

Postman Tutorial for Automation

Postman Tutorial for Automation

This step by step guide is a detailed documentation on Postman Tutorial for Automation. It will run you through all the steps that you would require to Automate API testing using Postman. Right from downloading Postman from Chrome to testing it for Automation.

Why Automation and Postman?

Automation is the new norm across sectors. Automation, using postman in testing can improve and increase the depth and scope of tests for a better software quality.

This postman tutorial will not only help you to understand the automated testing process but also help you to run postman in chrome and introduce API automation to your daily QA processes for executing repeated test cases.

Reading this Postman tutorial will help you to

1. Create test suites
2. Store information for running tests in different environments
3. Store data for use in other tests
4. Easily move tests and environments to code repositories

Need for Postman Automation

Postman Automation is truly important while testing products with a large number of integrations and/or frequent releases.
It is the ultimate tool for API automation. The main objective of QA automation is to reduce the combined amount of effort required for manually re-testing of a product which is fairly high.
Also, for removal of the manual testing efforts that are invested in testing a set of functionalities repeatedly.
For instance, Agile practices like continuous builds, the amount of time taken to receive a feedback for a manual regression test with the new code is too high. 

API testing is also known as Integration testing. Integration testing focuses on verifying that the interactions of many small components can integrate together without issue. Since API tests bypass the user interface, they tend to be quicker and much more maintainable than GUI tests. Therefore, a good QA team will make fairly accurate projections based on the backlog at hand and the general information about the project and its architecture and use automation for regression test.

Insights into Postman Tutorial for API Automation

 

Postman a Chrome app is for interacting with HTTP APIs. Postman allows user to automate test cases in javascript with salient features like write test suites, build requests that can contain dynamic parameters, pass data between requests, etc.

For validation of API, on receiving a response, Postman validates the response as described in the test scripts. This is performed under “Tests” section. Most interesting part is a JSON response can be parsed to an array and then the elements can be accessed by index and value or even be iterated.

The main benefit of using postman is that user does not need to create a full JSON request programmatically unlike other automation API frameworks to put assert on it. Postman beautifully designs them and helps user directly define test cases.

Tools/Dependency to get started –
1. Postman
2. Node
3. Newman

Installing Postman from Chrome

1. Visit https://chrome.google.com/webstore/category/extensions
2. Enter “Postman Chrome” in “Search the store” section
3. In App section postman will be listed
4. Click on “ADD TO CHROME

Introduction to Newman

Newman is Postman’s collection runner engine that sends API requests, receives the response and then runs your test against the response.It is like postman’s command line companion.It is extensible and so can be integrated into continuous integration servers and build systems.

Benefits of using Newman

1.Makes it easy to run a collection of tests using command line
2.Gives ability to run a collection of tests written in postman right from within most build tools
3.It allows to generate and store report directly from command line
Installing Newman

How to install Node with Newman:-

For Windows Refer below blog :-
 http://blog.getpostman.com/2015/04/09/installing-newman-on-windows/

For Ubuntu follow below mentioned steps :-

• Install Curl – sudo apt-get install curl
# Adding the NodeSource APT repository for Debian-based distributions repository AND the PGP key for verifying packages
• $ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash –
# Install Node.js from the Debian-based distributions repository
• $ sudo apt-get install -y nodejs
# Install newman from npm modules
• $ sudo npm install -g newman

Postman tutorial for Newman integration

Newman is a companion tool for postman that runs Collections from the command line.

Newman maintains feature parity with Postman and allows user to run collections in a similar way they are executed inside the collection runner in the Postman app.

Example :-

newman run postman_collection.json -e environment.postman_environment.json -g globals.postman_globals.json –reporters cli,html

The above command will be illustrated below in the article.
How to use postman
Creating First script using postman
Let us now learn on how to create test scripts using POSTMAN.
As we know, Postman allows to write the test scripts in Tests section. In our first script we will see how to check our response data.

• Open the postman app and enter the URL :-

For Example https://reqres.in/api/users?page=2

• Choose GET method. (By default GET is selected)
• Now click on Tests section. (Below the url section)
• Copy-paste below test script in Tests section

//First Test Case
tests[“Status code is 200”] = responseCode.code === 200;

//Second Test Case
tests[“Body matches string”] = responseBody.has(“gob”);

//Third Test Case
var jsonData = JSON.parse(responseBody);
tests[“Response should have id of gob as 5: ” ] = jsonData.data[1].id === 5;

//Fourth Test Case
tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === “bluth”;

• Click on Send button.
Above example includes 4 test cases.
• The first test case is checking for the response code of API. The Pass condition for the test case should be 200 (response code).
• The second test case is validating for any key or value as :- gob.
• The third test case is validating for a value of key id as 5 from JSON response.
• The fourth test case checking for the value of key “bluth” as “Newman” from JSON response.

To verify the test results, click on Tests as shown in image below.

Postman test script case 2

Variables

In this Postman tutorial for Automation we are also going to cover variables. There are two types of variables – global and environment. Global variables are for all collections whereas the environment variables are defined for a specific set of collections as per the environment which can be selected from a drop-down or no environment can be selected. Once defined variables can be used in request with format surrounded by curly brackets: {{VARIABLE_NAME}}. This can be seen in the image below.Variable in Postman

The global variables are variables which can we consumed by any collection. So for any data that is accessible for all collections, we define them as global variables.
The data defined for a specific environment is called as Environmental variable. We can select any one environment at a time for a collection or no environment as per choice.
• In Postman, at the top right section, click on (*) icon.
• Now click on MANAGE ENVIRONMENTS (refer the image below)

Manage Environments in Variables for Postman
• All the existing environments will be listed under Manage Environments.
• To create an environment, click on Add button at the bottom of the pop-up and enter a new Environment.
• To add a global variable, click on the Globals button listed at the bottom of the pop-up.
• For setting a new variable(global and environment), we need to define the New key and Value.

Pre-Request Script

Next in this Postman Tutorial is Pre-Request Scripts. As the name suggests will run before Tests.Postman allows users to perform specific JavaScript coding to manipulate the data being sent along with the request. We can write these scripts in Tests section also but it is a good practice to separate these scripts in pre-request section as the it will be executed prior to Tests scripts . Here we can set Global and Environment Variable dynamically as well.
Please refer the below image for the execution flow:

Execution flow for pre request script
• Copy-Paste the below code in Pre-request Script section in Postman :-
postman.setGlobalVariable(“Token”, “MyDemoToken”);
postman.setEnvironmentVariable(“MyKey”, “MyDemoKey”);
postman.getGlobalVariable(“MyDemoKey”);
console.log(“Global Variable = “+postman.getGlobalVariable(“Token”));
console.log(“Environment Variable = “+postman.getEnvironmentVariable(“MyKey”));
• Select an environment from the dropdown located at the top right section of the screen.
• Click on “Send”
• Now go to Global and Environment variable section.
• Observe that keys have been set dynamically by the script.

Dynamic key setting
To see console output of script use below steps

1. Type chrome://flags/#debug-packed-apps in the URL bar in your Chrome browser window.
2. Look out for “Debugging for packed apps”.
3. Enable the setting.
4. Click on Relaunch Now once the setting is enabled.
5. Type chrome://inspect/#apps in the URL bar and then click “inspect”

Note :- Collection Runner is opened as different instance of postman. To get the console output of collection runner, click on the Inspect link of the respective instance from Apps section.

console output of collection runner

Feeding Test Data from CSV and Variable

Predetermined value (Hard coded) is never a good practice and will be a pain when the number of test cases are increasing day by day. It will be a nightmare to maintain test scripts when your tests starting failing due to structural or data changes.

Refer below link for getting data from CSV :-
http://blog.getpostman.com/2014/10/28/using-csv-and-json-files-in-the-postman-collection-runner/
Refer below link for getting data from global and environment variables :-
https://www.getpostman.com/docs/postman/environments_and_globals/variables

Let us consider an example for passing data with the help of CSV.

1. Replace the below code in Tests Script section in Postman :-

 

tests[“Status code is 200”] = responseCode.code === 200;

tests[“Body matches string”] = responseBody.has(“gob”);

var jsonData = JSON.parse(responseBody);

tests[“Response should have id of gob as 5: ” ] = jsonData.data[1].id === data.id;

tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === data.name.trim();

console.log(“id =”+data.id+” “+”name =”+data.name);

2) Now we need to create a new collection to save the API. Follow the below steps to create a new collection.

• Click on Add button icon under Collections.
• Enter a Collection Name.
• Click on Create button.
• Once the Collection is created, click on Save button on right side of the screen.
• On Save Request pop-up, enter the Request name and select collection from the dropdown.
• Click on Save.

3) Now create a csv as illustrated below:

Example :–g
id,name
5,bluth

4) With the help of the CSV, let us run the test cases

• Now open the collection runner.
• Click on “Run” button.
• Select No environment or the environment whose keys are consumed in your Tests.
• Select csv file under Data File (The file created in Step 3).
• In Data File Type, select CSV from dropdown.
• Click on Start Test.

Start Test

Run Testcase from command line using newman

Earlier in this postman tutorial, under the title “How to install Node with newman”, we have already covered newman installation and configuration.

Now once the test cases are built, we need to pass it newman to run these scripts from the command line. The basic idea of running these tests using command line is that we can pass them to Jenkins further, which in return will run the test cases periodically. Now, to run the test cases in Newman, we need to export the test scripts and other information like URL, headers etc from postman in JSON format.

For more details refer below link:-

https://www.getpostman.com/docs/postman/collection_runs/command_line_integration_with_newman

Steps to export JSON for newman :-
1. In postman, under Collections section, select the required collection.
2. Click on Export as shown in the image below.
3. Select “Collection v2”
4. Click on Export
5. Save this JSON

Saving to JSON

Now we need to export global and environment variables if the script is consuming any of them.

Steps to export JSON of global and environment variables for newman :-

1. In postman, click on the (*) located at the top right section.
2. Click on Manage Environment
3. Now click on download icon placed against the environment name
4. Save the JSON on the same location where collection was saved
5. Now to download global variables,click on the “Globals” button placed at the bottom of the pop-up.
6. Click on “Download as JSON” button.
7. Save the JSON on the same location as others.

Saving JSON in Postman

Now, we have all the JSON files required to run our test cases in Newman. The collection JSON – contains all our test scripts, URL, Headers, Prerequisite Script etc contains most of the data except variables. The other two JSON files contain our key and values respectively.

Now it’s time to run our test cases from command line

Steps to run test cases from command line :-

• Open CMD
• Now reach to the folder where your JSON are saved
• Now hit command as below

newman run Test_Collection.postman_collection.json -e Environment.postman_environment.json -g globals.postman_globals.json -d demoData.csv –reporters cli,html

In above command -e represents environment variable, -g global variable, -d csv data file name, –reporters cli,html represents output as console and
html reports.

Note :- Replace respective file name in the above command.

Running Command in Postman

As soon as the execution is completed, Newman will create an execution report in same folder.

Postman Tutorial for Best Practices of Automation testing

1. Use trim function if data is retrieved as String from the CSV file.
2. Add your pre-request data in Pre-request Script section.
3. Use chrome dev console for debugging.
4. Always check the length of an array for a test case. It will safeguard the script from failing due to javascript exception
Example :-

if(jsonData.data[0].length>2)
{
tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === “bluth”;

Advantages of using Postman

 

1.If API is updated and test is run in postman, it gives indication of failure.The API can then be updated for correct results.

2.Postman can be used for performance testing of API.

3.Postman can be used to perform load testing at scheduled time and record the status

4.As the API’s are automated using postman there is less human involvement

Summary

We hope that this Postman Tutorial was helpful and we can safely conclude from the above information that API automation is a very important task in software development and postman tool caters best to all the requirements needed for an efficient API testing process.So try it out to get a stronghold on API’s.