Interview #84: Write a Postman Test script to check the response status code

Interview #84: Write a Postman Test script to check the response status code

In Postman, you can write test scripts using JavaScript to validate API responses. One of the fundamental tests is checking whether the response status code matches the expected value.

Disclaimer: For QA-Testing Jobs, WhatsApp us @ 91-9606623245

Steps to Write a Simple Test Script in Postman:

Open Postman and Select a Request:

  • Open Postman and create or open an existing request (e.g., a GET request to an API endpoint).

Go to the "Tests" Tab:

  • In the request editor, click on the "Tests" tab. This is where you can write JavaScript code to validate responses.

Write a Test Script to Check the Response Status Code:

  • Use the following JavaScript snippet inside the "Tests" tab:

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

Here’s what this script does:

  • pm.test("Status code is 200", function () {...}): Defines a test case with a descriptive message.
  • pm.response.to.have.status(200): Checks if the response status code is 200. If it matches, the test passes; otherwise, it fails.

Run the Test:

  • Click the "Send" button to execute the request.
  • Navigate to the "Test Results" section to check if the test passed or failed.

Customizing the Status Code Check

  • If you expect multiple status codes (e.g., 200 or 201), modify the script like this:

pm.test("Status code is 200 or 201", function () {
    pm.expect([200, 201]).to.include(pm.response.code);
});        

  • To verify that the status code falls within a range (e.g., 200-299 for successful responses):

pm.test("Status code is in the 2xx range", function () {
    pm.expect(pm.response.code).to.be.within(200, 299);
});        

Running Tests in Postman Collection Runner

If you want to automate testing for multiple requests:

  • Save your request in a Collection.
  • Open the Collection Runner and execute all requests.
  • Postman will display test results for each request.

Conclusion

Writing a test script in Postman to check the response status code is an essential practice in API testing. It helps ensure that the API behaves as expected and returns the correct HTTP status. You can extend this basic test by checking other aspects like response time, headers, and body content for a more comprehensive validation.


Nadia Belara

Software Tester at Accenture

3 周

Love this

回复

要查看或添加评论,请登录

Software Testing Studio | WhatsApp 91-9606623245的更多文章

社区洞察

其他会员也浏览了