Thursday 28 December 2017

How software testers can create dynamic mocked JSON responses, no programming skills needed!

The recommended way of creating mocks or stubs of third party or backed systems and APIs is to keep them as simple as possible.  Unfortunately, sometimes it is not possible to keep things simple, and it is necessary to create more complex systems or API simulators. In this example, we will go through an example how to create a simulator of an API that will dynamically generate a list of items in a response based on a request.

Let us assume that your application will send the following requests to a backend API:
{
  "orderId": 3,
  "storeId": 2244,
  "orderItems": [
    {
      "partnumber": "101",
      "quantity": 1
    },
    {
      "partnumber": "102",
      "quantity": 3
    }
  ]
}
And, let us assume that the response from that backend API looks like this:
{
  "orderAccepted": true,
  "orderItems": [
    {
      "orderItemId": 101,
      "quantity": 1
    },
    {
      "orderItemId": 102,
      "quantity": 3
    }
  ],
  "subordersCount": 2
}
Notice, that the request contains a list of items "orderItems" that is then populated in the response. So, to create the response dynamically, we need to parse the request JSON and create the response JSON based on the request. We can do that using the Traffic Parrot jsonPathList helper.

Let us also assume that we would like to accept the order only if the number of items in the request is even and reject it if the number is odd. To do that we can use the ifEven helper.

Here is a response body that you can copy and paste into Traffic Parrot that will generate a response dynamically based on the request:
{
  "orderAccepted": {{#ifEven (size (jsonPathList request.body '$.orderItems'))}}true{{else}}false{{/ifEven}},
  "orderItems": 
    [
      {{#each (jsonPathList request.body '$.orderItems') }}
           {
          "orderItemId": {{ jsonPath this '$.orderItemId' }},
          "quantity": {{ jsonPath this '$.quantity' }}
        }
        {{#unless @last}},{{/unless}}
      {{/each}}
    ]
  "subordersCount": {{size (jsonPathList request.body '$.orderItems')}}
}
Configuring a HTTP response in Traffic Parrot
This approach does not require knowledge of any programming languages, so almost anybody can do it. You can use this approach for HTTP(S), JMS, MQ and Files simulators. To get started with Traffic Parrot have a look at the quick start guide. Contact us for a free initial 30-minute consultation.




No comments:

Post a Comment