Email Subscription Form

Saturday, April 7, 2018

Adding Postman Assertions

This week, we'll be talking about adding assertions to our Postman requests.  In last week's post, we discussed what various API request responses mean, and how to write assertions for them in Postman requests.  Now we'll be adding some more assertions that will test our requests more fully. 

We will be using the Postman collection that we created two weeks ago, so if you haven't yet created that, you may want to set it up before you continue. 

The first type of assertion we'll discuss is the Response Time assertion.  This verifies that the response to an API request is returned within an acceptable amount of time. Let's say that the product owners of the Swagger Pet Store have decided that their end users should be able to add a new pet to the store in under one second.  We'll add an assertion for this to our Add Pet request.  Click on the Add Pet request in the collection list on the left of the screen so it will open up in the main window. Then click on the "Tests" tab.  You should already have the Response Code assertion that you added last week.  Click underneath that assertion, and then click on the "Response time is less than 200 ms" code snippet on the right.  This will be added to the Tests window:

pm.test("Response time is less than 200ms", function () {
    pm.expect(pm.response.responseTime).to.be.below(200);
});

Currently the test is asserting that the response time should be less than 200 milliseconds.  We don't need it to be that fast, so let's change the assertion.  First, change the "Response time is less than 200ms" to be "Response time is less than one second".  This is the title of the test.  Now let's change the actual assertion.  Change the value in "to.be.below" from 200 to 1000 (this is one thousand milliseconds, or one second).  Save your request and click the Send button.  You should see in the Test Results section at the bottom of the screen that your assertion passed.  You can also look at the top of the results window and see the response time next to the response status code. 

Another helpful assertion is the Response Contains String assertion.  This simply asserts that the body of the request response has a certain string.  I often use this assertion when I am expecting an error message.  To see this in action, let's add a new negative test to our collection.  We will trigger a 500 response by trying to add a pet to the store with a non-integer id. The easiest way to create this request will be to copy the existing Add Pet request and rename it to "Add Pet With Invalid ID". (If you don't know how to copy and rename a request, see Creating a Postman Collection.) 

We have a few changes to make to this request before we add in our new assertion.  In the body of the request, we'll change the id of pet from "100" to "FOOBAR".  Because we copied this request, we already have a couple of assertions in it: one that asserts that the response code will be 200, and one that asserts that the response time is less than 1000ms.  We know that our response code won't be 200 any more, so let's change that test to read:

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

We can leave the Response Time assertion as is, or we can remove it.  Now we can add in our new assertion.  Look in the snippet list for "Response body:Contains string", and click on it.  This will be added to the Test window:

pm.test("Body matches string", function () {
    pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});

Let's rename the assertion from "Body matches string" to "Error response is returned", and change the response text from "string_you_want_to_search" to "something bad happened". It's worth noting at this point that Postman assertions are case-sensitive, so you won't want to capitalize the word "Something", since it's not capitalized in the actual response.

Click the Send button and verify that you get Pass messages for both your Status Code test and for your Response Contains String test.

Now let's look at a more powerful assertion: the JSON Value Check.  We can actually assert that the values returned in a response are the values that we are expecting.  Let's look at the Get Pet request.  We are already asserting that the response code is 200, but that doesn't really tell us much.  It's possible that when we make our request that we are getting the wrong pet in the response!  We'll want to assert that we are getting the right pet back without having to physically look at the response. So we'll add a JSON Value Check.  Click below the Response Code assertion, and then look for the code snippet called "Response body: JSON value check". Click on this snippet.  This will be added to your test window:

pm.test("Your test name", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.value).to.eql(100);
});

Change the test name from "Your test name" to "Body contains pet id". Notice that the next line of code creates a variable called jsonData. This is the parsed version of the JSON response. On the third line, we'll change "jsonData.value" to "jsonData.id". This is because we want to find out what the id of the response is.  Finally, we don't need to change the value in "to.eql", because we were looking for an id of 100, and that's what it's already set to. When you are done making your changes, the assertion should look like this:

pm.test("Response contains id", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.id).to.eql(100);
});

Save your request changes and then click the Send button.  Both your Response Code assertion and your JSON Value Check tests should pass.

You may have noticed that there are other ids in the body of the Get Pet response:

{
    "id": 100,
    "category": {
        "id": 1,
        "name": "Cat"
    },
    "name": "Grumpy Cat",
    "photoUrls": [
        "https://pbs.twimg.com/profile_images/948294484596375552/RyGNqDEM_400x400.jpg"
    ],
    "tags": [
        {
            "id": 1,
            "name": "Mixed breed"
        }
    ],
    "status": "available"
}

 How would we assert on the category id or the tag id?  We do this by parsing through the JSON response. In order to demonstrate this, copy the test you just created, and edit it to look like this:

pm.test("Response contains category id", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.category.id).to.eql(1);
});

We've changed the test name in the top line of the code to reflect what we are actually asserting.  The second line of code remains the same. In the third line of code, we've changed "jsonData.id" to "jsonData.category.id". This means that instead of looking at the id, we are looking at the category section, and then at the id within that section. Finally we changed the value that we were expecting from 100 to 1. 

Save your request and click the Send button again. Now you should see all three assertions on the request pass.

Now that you know how to create assertions, you can go through all of the requests in your Pet Store collection and add your own! You may have noticed that your POST and PUT requests return the pet in the body of the response, so you can add similar assertions to those requests.  You'll definitely want to make sure that after you have changed your pet data with the PUT (Update Pet) request, the data you get back from your GET (Verify Update Pet) request has the updated information that you are expecting. 

This is just the beginning of what you can do with assertions!  Next week, we'll take a look at how to set variables and use them in both your requests and your assertions. 

18 comments:

  1. Hi,

    My Json response has key value pairs as this

    validity : 720.

    But when I use this

    pm.test("Response contains id", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.validity).to.eql(720);
    });


    An error saying validity is not defined or an undefined is expection to have blah blah blah. Where do I define validity as variable and when I am expecting it to be taken from response body, how can I define it before?


    ReplyDelete
    Replies
    1. Hi Sumithra- there are a couple of possibilities for what's wrong here. Does the data of the response contain the key "validity"? And is 720 a number or a string? If it's a string, you should put it in quotation marks. I hope this helps!

      Delete
    2. Investment plans
      PROMO PACKAGE
      ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡
      ๐Ÿ”Š BASIC
      ๐Ÿ’ŽInvest $200 earn $2,000
      ๐Ÿ’ŽInvest $300 earn $3,500
      ๐Ÿ’ŽInvest $400 earn $4,500
      ๐Ÿ’ŽInvest $500 earn $6,000

      ๐Ÿ”Š PRO
      ๐Ÿ’ŽInvest $1,000 earn $15,000
      ๐Ÿ’ŽInvest $2,000 earn $25,000
      ๐Ÿ’ŽInvest $3,000 earn $35,000
      ๐Ÿ’ŽInvest $4,000 earn $45,000
      ๐Ÿ’ŽInvest $5,000 earn $60,000
      ๐Ÿ’ŽInvest $10,000 earn $100,000.

      ๐Ÿ”Š PREMIUM
      ๐Ÿ’Ž1BTC earn 5BTC
      ๐Ÿ’Ž2BTC earn 10BTC
      ๐Ÿ’Ž3BTC earn 16BTC
      ๐Ÿ’Ž4BTC earn 22BTC
      ๐Ÿ’Ž5BTC earn 30BTC.

      ๐Ÿ’กALL RETURNS ARE SCHEDULE, FOR 12 HOURS, UPON CONFIRMATION OF PAYMENTS.

      ๐Ÿ’ฐMODE OF PAYMENT.
      Any, Suitable For Investors, But Terms and Conditions Apply.

      ⭐️HURRY NOW!!!
      Refer a Friend or Family member to invest same time, and Receive an instant $50 Reward.

      ๐Ÿ“ŒTo set up an INVESTMENT PLAN,
      Contact Admin: totalinvestmentcompany@gmail.com

      WhatsApp: +1(929)390-8581

      Visit this link for more prove https://www.facebook.com/pg/Total-Investment-221964325813140/about/

      For more prove link our YouTube
      https://www.youtube.com/channel/UC3KWT9dTpFLi0S0vJTWuCJg

      https://t.me/totalinvestment

      Delete
  2. Hi Kristin,

    Thanks for the reply. But the issue was, I didn't specify the object number of Validity here: as jsonData[0].validity. It worked once I added this.

    Thanks again.
    Sumithra.

    ReplyDelete
    Replies
    1. Hi Sumithra! Adding in the [0] is usually necessary when you have a response that is an array. The Pet Store may have changed since I first wrote this post. Thanks for the tip!

      Delete
    2. BEST CRYPTOCURRENCY INVESTMENT PLATFORM
      If you are seeking to invest in cryptocurrency and get good return on investment ROI , I will suggest you contact ELITECREDITANDINVESTMENT@GMAIL.COM to get the best signals , predictions and investment programs that suit your financial capabilities . Thank me later for this . I invested in several tokens, polkadot and dogecoin when they were at their least value and cashed out when they were at their peak before they started dropping again. This and many more investment opportunities I have benefited from this investment platform . contact ELITECREDITANDINVESTMENT@GMAIL.COM to get the best ROI ICO and crypto investment programmes .
      I was able to gain over $250.000 in profits from my investments ,also my withdrawal was smooth and successful

      Delete
  3. Hi everybody, I hope you are doing good. Dear admin I had scroll down your site and found it really useful for web development tools. Since I am a developer, I most often refer people to use best website in the town for web development. Your efforts are really appreciable. We also provide web development tool. Here is the link of our site jsononline

    ReplyDelete
  4. Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work ุชุญูˆูŠู„ word ุงู„ู‰ pdf

    ReplyDelete
  5. Are you interested in trading bitcoin binary and forex trade where you can earn 100% of your investment daily If you invest as low as $200 you will get a profit of $2,000 after 72 hours if you are intrested you can contact him via email: hackintechnology@gmail.com +12132951376(WHATSAPP)

    ReplyDelete
  6. Apply for loan here personal loan Easy Loan's available here apply from $3,000 to $20,000,000 within 24 hours upon request. Other types of loans are also available in less than 48 hours. Contact me as needed. Contact Us At : abdullahibrahimlender@gmail.com
    whatspp Number +918929490461
    Mr Abdullah Ibrahim

    ReplyDelete
  7. If you are in need of financial Help, don't hesitate to place order for deserve Programmed card that can withdraw any amount limit you want. Deserve Card are very transparent aand easy to deal with. You can Purchase Deserve card that can withdraw up to $50,000 to $100,000 limit without being detected because of the programming of the card. I'm extremely grateful to them for being honest with their words and delivering the card to me. This is the third day of receiving the card and i have withdraw $9,500 from the Deserve Programmed Card. I tried purchasing the card previously from someone else, but it never arrived until i tried skylink technology for those in need of more money, you can also contact them. you can place order for the card Via whatsapp / telegram+1(213)785-1553 or their E-mail: skylinktechnes@yahoo.com

    ReplyDelete
  8. Are you desperately in need of a hacker in any area of your life??? then you can contact; ( www.hackintechnology.com services like; -hack into your cheating partner's phone(whatsapp,bbm.gmail,icloud,facebook, twitter,snap chat and others) -Sales of Blank ATM cards. -hack into email accounts and trace email location -all social media accounts, -school database to clear or change grades, -Retrieval of lost file/documents -DUIs -company records and systems, -Bank accounts,Paypal accounts -Credit cards hacker -Credit score hack -Monitor any phone and email address -Websites hacking, pentesting. -IP addresses and people tracking. -Hacking courses and classes CONTACT THEM= hackintechnologyatgmaildotcom or whatsapp +12132951376 their services are the best on the market and 100% security and discreet work is guarante

    ReplyDelete
  9. Nice and interesting post, I appreciate your hard work. keep it up…!!!Thanks for such useful information, It is true that now if you want to grow your business you will surely need the mobile app testing services for your business. But for that purpose everyone needs best mobile app testing companies.

    ReplyDelete
  10. Do you need Personal Finance?
    Business Cash Finance?
    Unsecured Finance
    Fast and Simple Finance?
    Quick Application Process?
    Finance. Services Rendered include,
    *Debt Consolidation Finance
    *Business Finance Services
    *Personal Finance services Help
    contact us today and get the best lending service
    personal cash business cash just email us below
    Contact Us: financialserviceoffer876@gmail.com
    call or add us on what's app +918929509036

    ReplyDelete
  11. i was lost with no hope for my wife was cheating and had always got away with it because i did not know how or

    always too scared to pin anything on her. with the help a friend who recommended me to who help hack her phone,

    email, chat, sms and expose her for a cheater she is. I just want to say a big thank you to

    HACKINTECHNOLOGY@CYBERSERVICES.COM . am sure someone out there is looking for how to solve his relationship problems, you can also contact him for all sorts of hacking job..he is fast and reliable. you could also text +1 213-295-1376(whatsapp) contact and thank me later

    ReplyDelete
  12. Contact this guy for problems such as hacking emails, Facebook, Twitter, Instagram, note changes, deleting criminal records, credit and debit refill, reloading insurance documents, lost or lost file recovery, background check of people and organizations Monitor your spouse's activities regarding the phone and social media and contact him at BESTSYSTEMHACKSOLUTION@GMAIL.COM or text him on WhatsApp +1 (602) 609-4730 he is very trustworthy.

    ReplyDelete

New Blog Location!

I've moved!  I've really enjoyed using Blogger for my blog, but it didn't integrate with my website in the way I wanted.  So I&#...