Mar 9, 2021

API Testing 'A Beginners View': Response Validation With Assertions | Quick Guide on Assertions

The most important step in any API development is to check its functionality whether it is constructed to simulate the use of the API by end-user applications and fulfill the provided business requirements. There are several API testing frameworks and tools for getting the job done. Postman is one such tool that is handy and easy to use and offers features like create and send any HTTP requests, write test cases to validate response data, response times, analyze the responses sent by the API, create integration test suites and integrate with build systems.

Today we will discuss the commonly used Assertions while validating responses in POSTMAN.

Before jumping into the Test Scripts, let’s know some facts on Assertions.

Assertions: Assertion is nothing but code that can be used to check or analyze the response that is received from the server. An assertion is a code written in javascript in Postman that is executed after receiving the response. Assertions help us to assert that expected and actual values should match during a test run. If the actual and expected values don't match, then the test will fail with the output pointing to the failure.

Test cases in Postman:
(Note: In the Postman app, the request builder at the top contains the Tests tab where you write your tests. The response viewer at the bottom contains a corresponding Test Results tab where you can view the results of your tests)

To start building test cases quickly, commonly-used snippets are listed below.
Response to be asserted:
[
    {
        "type": "configuration/entityTypes/HCP",
        "tags": [
            "Jency Test Data",
            "Integration Testing",
            "FCQA"
        ],
        "attributes": {
            "Country": {
                "value": "Brazil"
            },
            "TypeCode": {
                "value": "Nurse"
            },
            "FirstName": {
                "value": "Daniele"
            },
            "LastName": {
                "value": "Bedward 2021-03-09 03:55:47"
            },
            "Prefix": {
                "value": "MISS."
            },
            "Gender": {
                "value": "Polygender"
            },
            "StatusIMS": {
                "value": "Active"
            },
            "PresumedDead": {
                "value": "false"
            },
            "InternationalHCP": {
                "value": "FALSE"
            },
            "ClinicalTrials": {
                "value": "false"
            },
            "PrivacyPreferences": [
                {
                    "value": {
                        "OptOut": {
                            "value": "false"
                        },
                        "AllowedToContact": {
                            "value": "false"
                        },
                        "PhoneOptOut": {
                            "value": "false"
                        },
                        "EmailOptOut": {
                            "value": "false"
                        },
                        "FaxOptOut": {
                            "value": "false"
                        },
                        "VisitOptOut": {
                            "value": "false"
                        },
                        "TextMessageOptOut": {
                            "value": "false"
                        },
                        "MailOptOut": {
                            "value": "false"
                        },
                        "RemoteOptOut": {
                            "value": "false"
                        },
                        "OptOutOneKey": {
                            "value": "false"
                        },
                        "KeyOpinionLeader": {
                            "value": "false"
                        },
                        "ResidentIndicator": {
                            "value": "false"
                        }
                    }
                }
            ],
            "Specialities": [
                {
                    "value": {
                        "SpecialtyType": {
                            "value": "Primary"
                        },
                        "Specialty": {
                            "value": "ENDOSCOPY"
                        },
                        "Rank": {
                            "value": 1
                        },
                        "PrimarySpecialtyFlag": {
                            "value": "true"
                        }
                    }
                }
            ],
            "ValidationStatus": {
                "value": "Valid"
            },
            "IsBlackListed": {
                "value": "false"
            },
            "RequiresAttention": {
                "value": "false"
            },
            "TriggerDCR": {
                "value": "false"
            },
            "Address": [
                {
                    "value": {
                        "PrimaryAffiliation": {
                            "value": "TRUE"
                        },
                        "AddressType": {
                            "value": "Private Practice"
                        },
                        "Country": {
                            "value": "Brazil"
                        },
                        "AddressLine1": {
                            "value": "100 Main Street"
                        },
                        "City": {
                            "value": "Rio de Janeiro"
                        },
                        "StateProvince": {
                            "value": "RJ"
                        },
                        "Zip": [
                            {
                                "value": {
                                    "Zip5": {
                                        "value": 10000
                                    }
                                }
                            }
                        ],
                        "VerificationStatus": {
                            "value": "Partially Verified"
                        },
                        "ValidationStatus": {
                            "value": "Valid"
                        },
                        "Status": {
                            "value": "Active"
                        },
                        "AVC": {
                            "value": "P22-I44-P2-100"
                        }
                    }
                }
            ]
        }
    }
]
Assertions to the above response is as below:
var resp = JSON.parse(responseBody);
console.log(resp);

//assert response time
pm.test("Response time Check"function () {
     pm.expect(pm.response.responseTime).to.be.below(3000);
     pm.expect(pm.response.responseTime).to.be.above(500);
});

//assert response status code
pm.test("Response is OK"function () 
{
    pm.response.to.have.status(200);
});
//assert - For checking status being BAD REQUEST
pm.test("Bad Request Check"function () {
     pm.response.to.not.be.badRequest;
});

// assert on response and response type
pm.test("Response should be okay to process"function () { 
    pm.response.to.not.be.error
    pm.response.to.be.json;
});

// assert on Response Header
pm.test("Content-Type is present"function () {
     pm.response.to.have.header("Content-Type");
});

//assert on multiple status code
pm.test("Successful POST request"function () {
     pm.expect(pm.response.code).to.be.oneOf([200,201,202]);
});

//assert on an array
for (var i = 0;i<resp[0].tags.length;i++
{
    console.log("Length of array is: " + resp[0].tags.length);
    console.log("Index Value during iteration is: " + i);
    pm.test("Tag is: " + resp[0].tags[i], function () 
    {
        pm.expect((resp[0].tags[i]) != null).to.be.true;
    });
    console.log("Tag is: " + resp[0].tags[i]);
}

//compare value of a response with an already defined variable
// Getting values from response
var FirstName = resp[0].attributes.FirstName;
// Saving the value for later use
pm.globals.set("FirstName"FirstName);
pm.test("Variable usage check"function () {
    pm.expect(resp[0].attributes.FirstName).to.eql(pm.globals.get("FirstName"));
});

You can also write your own custom tests in JavaScript using "Chia Assertion Library": Click Me.

Note: The above snippet is appended in my public Collection “API Testing 'A Beginners View'”

This posts will be continued with more "Assertions" in the coming days…

Until then…
Happy Testing 😇

2 comments:

Tanay patil said...

That's great news. We wish you good luck with your blogging journey and feel free to contact us in case you need anything.
go next page

Devya said...

Really well explained .thank you so much really helpful
learn more