0
0
Postmantesting~5 mins

Defining mock responses in Postman

Choose your learning style9 modes available
Introduction

Mock responses let you pretend a server sends data. This helps test your app even if the real server is not ready or slow.

You want to test your app before the real API is built.
The real server is down or slow, but you need to keep testing.
You want to check how your app handles different server replies.
You want to share a fake API with teammates for testing.
You want to simulate error messages from the server.
Syntax
Postman
1. Open Postman and create a new mock server.
2. Define the request URL and method to mock.
3. Add one or more example responses with status code, headers, and body.
4. Save the mock server and use its URL in your tests.

You can create multiple example responses for one request to test different cases.

Mock servers in Postman give you a URL that acts like the real API.

Examples
This example mocks a successful login response with a token and user name.
Postman
POST /login
Response 200
{
  "token": "abc123",
  "user": "john"
}
This example mocks a product list returned by the server.
Postman
GET /products
Response 200
[
  {"id":1, "name":"Book"},
  {"id":2, "name":"Pen"}
]
This example mocks an error response when the user does not exist.
Postman
GET /user/123
Response 404
{
  "error": "User not found"
}
Sample Program

This step-by-step shows how to create a mock server in Postman that returns a fake user detail.

Postman
1. In Postman, click 'New' > 'Mock Server'.
2. Choose 'Create a new collection' and name it 'User API'.
3. Add a request to the collection: GET https://api.example.com/user/1
4. Add an example response:
   - Status: 200 OK
   - Body: {"id":1, "name":"Alice"}
5. Save the example.
6. Create the mock server and copy its URL.
7. Use the mock URL in your app to get the fake user data.
OutputSuccess
Important Notes

Always keep your mock responses updated to match real API changes.

Use descriptive names for your examples to remember their purpose.

Mock servers help you test offline or when the real API is unstable.

Summary

Mock responses let you simulate server replies for testing.

Postman makes it easy to create and use mock servers.

Use mocks to test your app early and handle different scenarios.