DEV Community

TaheraFirdose
TaheraFirdose

Posted on

How To Automate API Testing With Postman

In this article, we will learn how to validate the response by writing test scripts and assertions for testing API using postman.

Postman is an excellent utility tool for creating integration tests for rest API endpoints because it allows you to write test scripts and add assertions. We can determine if a test passes or fails based on the output of these assertions.

Writing tests

In your requests and collections, you can use the Tests tab to write tests that will run when Postman receives a response from the API you requested. For each request, you can add as many tests as you need. When you add tests to a Collection, they will execute after each request inside it.

We can enter the script manually or use the Snippets, which is available on the right side of the code editor

image

Basic test syntax

The pm.* API is used to write your test under the Tests tab in Postman. The pm.test() method accepts 2 parameters.

  1. The first parameter is the name of the test(as a string), it's important to give your test a descriptive name so that you can provide more information if it fails.
  2. The second parameter is a function that will pass or fail the test if any assertions within your function pass/fail. The function returns a boolean (true or false)

Postman uses the Chai assertion library for creating assertions. It’s based on the BDD style of assertions which make it highly readable and understandable.

Test results

After you execute the request with the test scripts, go to the Tests tab in the response viewer. It will display a list of tests with the results passed or failed. A boolean which returns true is marked as passed while a boolean which returns false is marked as failed.

Writing test scripts

Scenario01: Verify the status code is 200

image

Scenario02: Verify status code contains a string. Example: 201 (created), 200(OK)

image

Scenario03: Verify the status code from a list of expected status code (include them all in an array and use one of)

image

Scenario04: Verify the response time is below 1000ms and above 100ms

image

Scenario05: Verify the presence of header and the value.

image

image

Scenario06: Verify the properties of the objects in response body

The below test include multiple assertions as part of a single test, Even if one assertions fails, the test as a whole will fail. All assertions must be successful for the test to pass

image

Scenario07: Verify the values in the response body

Response Body
image

image

Top comments (0)