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.
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
The pm.* API is used to write your test under the Tests tab in Postman. The pm.test() method accepts 2 parameters.
- 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.
- 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
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.
Scenario 06: Verify the properties of the objects in response body
Scenario 08: Verify the response value against a variable
Scenario 10 : Verify the response is valid and has a body and the bodytype is JSON
This article aims at showing you how to utilize Postman to write automated tests for your APIs which will allow you to bridge the gap between development and quality assurance, and also minimize the surface area of bugs in your API.