Monday 24 July 2023

How to Automate SOAP API using Rest Assured with real-time examples ?

 



Check below link for question and answers with the code:




Introduction:

💥SOAP (Simple Object Access Protocol) is a protocol used for exchanging structured information in the implementation of web services. It uses XML to define the message format and relies on HTTP, SMTP, TCP, or other transport protocols for message transmission.

💥Rest Assured is a Java library that provides a domain-specific language (DSL) for writing powerful and easy-to-read API tests for RESTful web services. It simplifies the process of testing RESTful APIs by providing a range of built-in functions and methods for making HTTP requests and validating responses. Rest Assured is widely used for automated API testing due to its simplicity and flexibility.


💥Before you jump into this post, make sure you know about the Automation of API methods like GET, POST, DELETE using Rest Assured, if not refer to the post here👉


Learn how to automate SOAP APIs using Rest Assured with real-time
examples. 

Rest Assured is a powerful Java library that simplifies API testing for SOAP web services. Follow our step-by-step guide and practical examples to efficiently automate your SOAP API tests. Boost your testing productivity and ensure the reliability of your webservices with this comprehensive tutorial. Get started today and
streamline your API automation process with Rest Assured.


To automate SOAP APIs with RestAssured, you need to set up the project dependencies, configure the test environment, and write test scripts. Below is an example of how to do this:

💥Step 1:

Set up the Project Create a new Java project in your favorite IDE and add the required dependencies. In this example, we'll use Maven for dependency management. Add the following dependencies to your pom.xml file:


<dependencies>
    <dependency>
        <groupId>io.rest-assured</groupId>
        <artifactId>rest-assured</artifactId>
        <version>4.3.3</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.testng</groupId>
        <artifactId>testng</artifactId>
        <version>7.4.0</version>
        <scope>test</scope>
    </dependency>
</dependencies>


Java Coding Interview Questions and Answers

GIT Interview Questions and Answers

💥Step 2:

Configure the Test Environment Create a new Java class for your test and configure the base URI for the SOAP API:


import io.restassured.RestAssured;
import org.testng.annotations.BeforeClass;

public class SoapAPITest {
    @BeforeClass
    public void setUp() {
        RestAssured.baseURI = "https://example.com/soap-api"; // Replace with your SOAP API URL
    }
}



💥Always make sure to learn about JSON when you are dealing with APIs:
Demystifying JSON: Understanding Simple JSON, JSON Arrays, and JSON Objects



💥Step 3:

Write Test Scripts Now you can start writing test scripts to interact with the SOAP API using RestAssured. Below is an example of how to make a SOAP request and validate the response:


import io.restassured.response.Response;
import org.testng.annotations.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

public class SoapAPITest extends BaseTest {
    @Test
    public void testSoapRequest() {
        String soapRequest = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " +
                            "xmlns:web=\"http://www.example.com/webservice\">" +
                            "<soapenv:Header/>" +
                            "<soapenv:Body>" +
                            "<web:YourSoapRequest>" +
                            "<web:Parameter1>Value1</web:Parameter1>" +
                            "<web:Parameter2>Value2</web:Parameter2>" +
                            "</web:YourSoapRequest>" +
                            "</soapenv:Body>" +
                            "</soapenv:Envelope>";

        Response response = given()
                .contentType("text/xml")
                .body(soapRequest)
            .when()
                .post("/your-soap-endpoint") // Replace with your SOAP endpoint
            .then()
                .statusCode(200)
                .body("Envelope.Body.YourSoapResponse", equalTo("ExpectedValue")) // Replace with your expected value
                .extract().response();

        // Print the SOAP response
        System.out.println(response.getBody().asString());
    }
}


Note: In the above example, you need to replace the placeholders (e.g., https://example.com/soap-api, /your-soap-endpoint, Value1, Value2, ExpectedValue) with your actual SOAP API URL, endpoint, request parameters, and expected values.

With the above setup and test script, you can now run your RestAssured tests to automate SOAP API testing efficiently.


💥How do I loop around Array, List and Map?


💥Lets take one more real time API example:

To automate the SOAP API (http://www.dneonline.com/calculator.asmx?WSDL) using Rest Assured, you'll need to use the Rest Assured library along with the SAAJ (SOAP with Attachments API for Java) library. 

In Rest Assured we do not have built-in support to handle SOAP directly, so we'll leverage SAAJ to handle the SOAP request and response.

Here's a Java code example to perform the "Add" operation using Rest Assured and SAAJ:

import org.testng.annotations.Test;
import io.restassured.RestAssured;
import static io.restassured.module.jsv.JsonSchemaValidator.*;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;

public class SoapApiTest {

    @Test
    public void testAddOperation() {
        String soapRequestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:tem=\"http://tempuri.org/\">\n"
                + "   <soapenv:Header/>\n"
                + "   <soapenv:Body>\n"
                + "      <tem:Add>\n"
                + "         <tem:intA>10</tem:intA>\n"
                + "         <tem:intB>20</tem:intB>\n"
                + "      </tem:Add>\n"
                + "   </soapenv:Body>\n"
                + "</soapenv:Envelope>";

        // Send the SOAP request using SAAJ and Rest Assured
        SOAPConnectionFactory soapConnectionFactory;
        SOAPConnection soapConnection = null;
        try {
            soapConnectionFactory = SOAPConnectionFactory.newInstance();
            soapConnection = soapConnectionFactory.createConnection();
            SOAPMessage soapRequest = MessageFactory.newInstance().createMessage(null,
                    new StringReader(soapRequestBody));
            SOAPMessage soapResponse = soapConnection.call(soapRequest, "http://www.dneonline.com/calculator.asmx");

            // Extract the response body from the SOAP response
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            SOAPBody responseBody = soapResponse.getSOAPBody();
            StreamSource source = new StreamSource(responseBody.extractContentAsDocument());
            StreamResult result = new StreamResult(System.out);
            transformer.transform(source, result);

            // Add your assertions here for validating the response
            // For example, you can use Rest Assured to validate the JSON response
            RestAssured.given().contentType("application/json").body(result.getWriter().toString())
                    .when().post("/your-validation-endpoint")
                    .then().assertThat().body(matchesJsonSchemaInClasspath("your-json-schema.json"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (soapConnection != null) {
                try {
                    soapConnection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

This code sends the SOAP request to the "Add" operation of the SOAP API, extracts the SOAP response, and then you can use Rest Assured to validate the JSON response against a JSON schema.

Keep in mind that Rest Assured is primarily designed for RESTful API testing, so using it for SOAP APIs requires a bit of additional work with SAAJ. For pure SOAP testing, you may consider using dedicated SOAP testing libraries like Apache CXF or Spring WS.

⭐️⭐️⭐️⭐️⭐️

📌YouTube channel:
https://lnkd.in/gHJ5BDJZ

📌Telegram group:
https://lnkd.in/gUUQeCha

📌Schedule 1:1 call:
https://lnkd.in/ddayTwnq

📌Medium blogs:
https://lnkd.in/gkUX8eKY

*******************************************************************
For any doubts or career guidance from me, reach out here : https://topmate.io/sidharth_shukla

********************************************************************

Do remember that knowing Linux is one of the most important aspect to work as an SDET.

Basic Linux Commands for Automation QA


****************************************

TOP 15 BDD - CUCUMBER Interview Q&A


************************************************

✍️AUTHORLinkedIn Profile

************************************************

Learn (API-Microservice)Testing+ Selenium UI Automation-SDET with Self Paced Videos prepared by FAANG employees and LIVE Doubt Session 

SDET TRANING VIDEOS AVAILABLE with Live Doubt Session Check Training Page for Course Content or reach out @whatsapp +91-9619094122. 
This includes classnotes, 500+ interview questions, 3 projects, Java Coding question set for product companies along with career guidance from FAANG employees for Automation and SDET.

For more details whatsapp : https://lnkd.in/dnBWDM33

Course_001API Automation +
UI Automation +
Mobile Testing +
ChatGPT For Test Automation +
Jenkins-GIT-Docker
Course_002API Automation +
UI Automation +
Jenkins-GIT-Docker
Course_003API Automation +
ChatGPT for Test Automation +
Jenkins-GIT
Course_004ChatGPT for Test Automation
Course_005API Automation +
Jenkins-GIT

************************************************


SeleniumWebdriver Automation Testing Interview Questions:

https://automationreinvented.blogspot.com/search/label/SeleniumWebdriver

API Testing Interview Question Set:

https://automationreinvented.blogspot.com/2022/03/top-80-api-testing-interview-questions.html

DevOps Interview Q&A:

https://automationreinvented.blogspot.com/2021/11/top-11-devops-interview-questions-and.html 

Kubernetes Interview Question Set

https://automationreinvented.blogspot.com/search/label/Kubernetes

Docker Interview Question Set

https://automationreinvented.blogspot.com/Docker

Linux Interview question Set

https://automationreinvented.blogspot.com/search/label/Linux

Automation Testing/SDET Framework Design

https://automationreinvented.blogspot.com/search/label/FrameworkDesign

Java Related Interview Question Set

https://automationreinvented.blogspot.com/search/label/Java

GIT Interview Question Set:

https://automationreinvented.blogspot.com/2021/09/top-40-git-interview-questions-and.html

Coding Interview Question Set:

https://automationreinvented.blogspot.com/search/label/Coding%20Questions

Mobile Testing Interview Question Set:

https://automationreinvented.blogspot.com/search/label/Mobile%20Testing

Python Interview Question Set for QAE - SDET - SDE:

https://automationreinvented.blogspot.com/search/label/Python

 

No comments:

Post a Comment

All Time Popular Posts

Most Featured Post

Sorting with Examples & Time Complexity for SDET

  🔺 LinkedIn: https://www.linkedin.com/in/sidharth-shukla-77b53145/ 🔺 Telegram Group:  https://t.me/+FTf_NPb--GQ2ODhl Bubble Sort:    Bubb...