Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Automated Testing Frameworks for Web APIs and SOAP Services

Tech May 13 1

RESTful API Testing Approaches

GUI-Based Testing with JMeter

JMeter provieds a visual environment for constructing API test scenarios. Configure a thread group to simulate concurrent users, then add HTTP Request samplers to target yourr endpoints. Attach a View Results Tree listener to inspect response details. For data-driven testing, incorporate a CSV Data Set Config element to parameterize requests with external data files. Reference variables using ${variableName} syntax within request parameters.

Programmatic Java Testing with HttpClient

Implementing GET Request Validation

public void validateGetEndpoint() throws URISyntaxException, IOException {
    // Initialize HTTP client instance
    CloseableHttpClient httpClient = HttpClients.createDefault();
    
    // Construct request URI with parameters
    URI requestUri = new URIBuilder()
        .setScheme("http")
        .setHost("localhost")
        .setPort(8080)
        .setPath("/api/calculator")
        .setParameter("operand1", "5")
        .setParameter("operand2", "7")
        .build();
    
    // Create and execute HTTP GET request
    HttpGet request = new HttpGet(requestUri);
    CloseableHttpResponse response = httpClient.execute(request);
    
    // Verify response status and extract content
    if (response.getCode() == HttpStatus.SC_OK) {
        String responseBody = EntityUtils.toString(response.getEntity());
        System.out.println("Response: " + responseBody);
    }
    
    response.close();
    httpClient.close();
}

Executing POST Request Verification

public void submitPostRequest() throws IOException {
    // Instantiate client and configure POST request
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost request = new HttpPost("http://192.168.1.100:8080/api/compute");
    
    // Prepare form-encoded parameters
    List<NameValuePair> parameters = new ArrayList<>();
    parameters.add(new BasicNameValuePair("valueA", "10"));
    parameters.add(new BasicNameValuePair("valueB", "20"));
    
    // Encode parameters and attach to request
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, StandardCharsets.UTF_8);
    request.setEntity(entity);
    
    // Execute request and process response
    CloseableHttpResponse response = httpClient.execute(request);
    if (response.getCode() == HttpStatus.SC_OK) {
        String result = EntityUtils.toString(response.getEntity());
        System.out.println("Result: " + result);
    }
    
    response.close();
    httpClient.close();
}

Data-Driven Test Automation Framework

@RunWith(Parameterized.class)
public class ApiParameterValidation {
    
    private final int inputA;
    private final int inputB;
    private final int expectedOutput;
    
    public ApiParameterValidation(int num1, int num2, int expected) {
        this.inputA = num1;
        this.inputB = num2;
        this.expectedOutput = expected;
    }
    
    @Parameterized.Parameters
    public static Collection<Object[]> dataSource() {
        return Arrays.asList(new Object[][] {
            {2, 3, 5},
            {5, 7, 12},
            {10, -5, 5}
        });
    }
    
    @Test
    public void verifyCalculationEndpoint() throws Exception {
        RestApiClient apiClient = new RestApiClient();
        int actualResult = apiClient.executeGetRequest(inputA, inputB);
        assertEquals(expectedOutput, actualResult);
    }
}

SOAP WebService Testing Methods

Visual Testing with SoapUI

SoapUI enables rapid SOAP service testing through WSDL import. Create a new project and provide the WSDL URL or file path. The tool generates request templates automatically. Modify the placeholder values within the XML payload and execute tests to verify service behavior.

Java-Based SOAP Service Testing

Stub-Based GET Implementation

public int invokeSoapService(int firstNum, int secondNum) throws RemoteException {
    String wsdlLocation = "http://10.0.1.50:8080/axis2/services/MathService?wsdl";
    
    // Generate service stub from WSDL
    MathServiceStub serviceStub = new MathServiceStub(wsdlLocation);
    MathServiceStub.SumOperation operation = new MathServiceStub.SumOperation();
    
    // Configure operation parameters
    operation.setFirstOperand(firstNum);
    operation.setSecondOperand(secondNum);
    
    // Execute operation and retrieve result
    SumResponse serviceResponse = serviceStub.sum(operation);
    return serviceResponse.getResult();
}

Manual POST with Raw SOAP XML

public static void executeSoapRequest(int operandA, int operandB) throws IOException {
    // Initialize HTTP client and POST request
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost soapRequest = new HttpPost("http://10.0.1.61:8080/axis2/services/Calculator?wsdl");
    
    // Construct SOAP envelope manually
    String soapPayload = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' "
                     + "xmlns:calc='http://calculator.service'>"
                     + "<soap:Header/>"
                     + "<soap:Body>"
                     + "<calc:addition>"
                     + "<calc:first>" + operandA + "</calc:first>"
                     + "<calc:second>" + operandB + "</calc:second>"
                     + "</calc:addition>"
                     + "</soap:Body>"
                     + "</soap:Envelope>";
    
    // Set request entity and content type
    StringEntity requestEntity = new StringEntity(soapPayload, StandardCharsets.UTF_8);
    soapRequest.setEntity(requestEntity);
    soapRequest.setHeader("Content-Type", "text/xml;charset=UTF-8");
    
    // Execute and output response
    CloseableHttpResponse response = httpClient.execute(soapRequest);
    System.out.println(EntityUtils.toString(response.getEntity()));
    
    response.close();
    httpClient.close();
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.