Mocking Services with Ballerina in a Minute

Suppose you are writing an integration scenario (in Ballerina or any technology), and you need to test the end-to-end scenario you just wrote. Way to achieve this is to mock a back-end service, and test your integration flow, without having to hassle with the actual back-end servers. With Ballerina, mocking a service has made easier than ever. All it takes is one minute to mock your service and make it up and running, with the flexibility of Ballerina. Lets look at how we can achieve this.


Prerequisites:


Mock the Service:


Lets consider a scenario where we need to test sending a payload to a back-end server, and receiving a different payload form it. Lets also assume following are the two pyaloads, we are sending to the back-end, and receiving from it, respectively.


Sending Payload:

<Order>
    <orderId>order100</orderId>
    <items>
        <item>
            <itemId>101</itemId>
            <price>2</price>
            <quantity>1</quantity>
        </item>
        <item>
            <itemId>106</itemId>
            <price>7</price>
            <quantity>2</quantity>
        </item>
    </items>
</Order>



Receiving Payload:

{
      "orderId":"order100",
      "status":"accpeted"
}

Lets create the mocked service to accept the above "sending payload" and send back the "receiving payload" as the response.

import ballerina.lang.xmls;
import ballerina.lang.messages;
import ballerina.lang.system;
import ballerina.net.http;

@http:BasePath{value:"/pizzaService"}
service PizzaService {

    @http:POST{}
    @http:BasePath{value:"/placeOrder"}
    resource placeOrder(message m) {

        // Get the order Id
        xml request = messages:getXmlPayload(m);
        string orderId = xmls:getString(request, "/Order/orderId/text()");

        // generate the json payload
        json responseJson = `{"orderId":${orderId}, "status":"accpeted"}`;

        // generate the response   
        message response = {};
        messages:setJsonPayload(response, responseJson);
        reply response;
    }
}

Don't we need to set the content type?

No, we don't need to. Ballerina will automatically set the content type to application/json, when we set a json as the payload!
Lets save this service in pizzeService.bal file.


Run the Mocked Service


To run our service, execute the following:
<ballerina_home>/bin/ballerina run service <path/to/bal/file>pizzeService.bal

Now the mocked service is up, and you can test your integration scenario using this service as the back-end.

Share:

0 comments