7 courses available at lowest price 1 day remaining

Getting Started with Postman Tests: A Practical Guide

Cover

One of the questions I get asked frequently is how to write tests in Postman. If you've been using Postman just to send requests and check responses manually, you're missing out on one of its most powerful features - automated testing.

In this article, I'll walk you through the basics of Postman tests using real examples from my Carsties auction application course. By the end, you'll understand how to validate responses, chain requests together, and run your tests as a complete integration test suite.

Why Write Tests in Postman?

Before we dive into the code, let's understand why you'd want to write tests:

  • Immediate feedback: Know instantly if your API is returning what you expect
  • Regression testing: Run your collection after changes to ensure nothing broke
  • Documentation: Tests serve as executable documentation of how your API should behave
  • CI/CD integration: Run your tests automatically in your deployment pipeline using Newman

Basic Status Code Assertions

The simplest test you can write checks the HTTP status code. Here's how to verify a successful response:

javascript
pm.test('Status code is 200', function() {
    pm.response.to.have.status(200);
});

For created resources, check for 201:

javascript
pm.test('Status code is 201', function() {
    pm.response.to.have.status(201);
});

And for deleted resources that should no longer exist:

javascript
pm.test('Status code is 404', function() {
    pm.response.to.have.status(404);
});

Working with JSON Response Data

Most APIs return JSON, and Postman makes it easy to parse and test this data. First, parse the response:

javascript
var jsonData = pm.response.json();

Now you can write assertions against the data:

javascript
pm.test('First item should be Audi R8', function() {
    pm.expect(jsonData[0].make).to.eq('Audi');
    pm.expect(jsonData[0].model).to.eq('R8');
});

Checking Property Existence

Sometimes you want to verify that certain properties exist in the response, regardless of their values:

javascript
pm.test('Response body contains expected properties', function() {
    pm.expect(jsonData).to.haveOwnProperty('id');
    pm.expect(jsonData).to.haveOwnProperty('make');
    pm.expect(jsonData).to.haveOwnProperty('model');
    pm.expect(jsonData).to.haveOwnProperty('year');
    pm.expect(jsonData).to.haveOwnProperty('seller');
    pm.expect(jsonData.status).to.eq('Live');
});

This is particularly useful when testing create endpoints where you want to ensure all required fields are returned.

Checking Array Length

When testing endpoints that return collections:

javascript
pm.test('Should be 10 items', function() {
    pm.expect(jsonData.length).to.equal(10);
});

Or for paginated responses:

javascript
pm.test('Result includes pagination properties', function() {
    pm.expect(jsonData).to.haveOwnProperty('results');
    pm.expect(jsonData).to.haveOwnProperty('pageCount');
    pm.expect(jsonData).to.haveOwnProperty('totalCount');
});

pm.test('pageCount is 3 and totalCount is 9', function() {
    pm.expect(jsonData.pageCount).to.eq(3);
    pm.expect(jsonData.totalCount).to.eq(9);
});

String Matching with include() and contain()

For partial string matching:

javascript
pm.test('Make includes updated', function() {
    pm.expect(jsonData.make).to.include('Updated');
});

Chaining Requests with Collection Variables

One of Postman's most powerful features is the ability to pass data between requests. This is essential for testing CRUD workflows.

Storing a value from a response:

javascript
pm.collectionVariables.set("createdItemId", jsonData.id);
pm.collectionVariables.set("createdItemModel", jsonData.model);

Using the value in subsequent requests:

In your request URL or body, reference the variable:

text
{{auctionApi}}/api/auctions/{{createdItemId}}

This allows you to:

  1. Create an auction and store its ID
  2. Update that specific auction
  3. Verify the update
  4. Delete the auction
  5. Verify it's been deleted (expect 404)

Pre-request Scripts

Sometimes you need to generate dynamic data before sending a request. Pre-request scripts run before the request is sent:

javascript
var date = new Date();
date.setDate(date.getDate() + 14);
var dateString = date.toISOString();
pm.variables.set("dateString", dateString);

This creates a date 14 days in the future - useful for auction end dates that need to be in the future.

Using Dynamic Variables

Postman provides built-in dynamic variables for generating random data:

  • {{$randomFirstName}} - Random first name
  • {{$randomColor}} - Random color
  • {{$randomInt}} - Random integer
  • {{$guid}} - Random GUID

Use these in your request body:

json
{
  "make": "Ford",
  "model": "{{$randomFirstName}}",
  "color": "{{$randomColor}}",
  "mileage": "{{$randomInt}}",
  "auctionEnd": "{{dateString}}"
}

This makes your tests more robust by not relying on hardcoded values.

Testing Microservices Integration

When working with microservices, you often need to verify that changes in one service propagate to another. For example, creating an auction in the Auction Service should make it searchable in the Search Service:

javascript
// After creating in Auction Service
pm.collectionVariables.set("createdItemId", jsonData.id);

// Then in Search Service test
pm.test('Item has been created in search', function() {
    var id = pm.collectionVariables.get('createdItemId');
    pm.expect(jsonData.results[0].id).to.eq(id);
});

Running Your Tests

You can run your tests in several ways:

  1. Single request: Click Send and check the Test Results tab
  2. Collection runner: Run all requests in a folder or collection in sequence
  3. Newman CLI: Run collections from the command line for CI/CD integration
bash
newman run Carsties.postman_collection.json -e environment.json

Summary

Postman tests transform your API exploration tool into a powerful testing framework. Start with simple status code checks, then gradually add response validation, variable chaining, and pre-request scripts as your testing needs grow.

The key patterns to remember:

  • pm.response.to.have.status() for status codes
  • pm.response.json() to parse JSON responses
  • pm.expect() with .to.eq(), .to.include(), .to.haveOwnProperty()
  • pm.collectionVariables.set() and .get() to chain requests
  • Pre-request scripts for dynamic data generation

Once you get comfortable with these basics, you'll find yourself writing tests for every API you work with. It's a habit that will save you countless hours of manual testing and help you catch bugs before they reach production.

Comments

to join the discussion.

Loading comments...