API Testing : Check malformed request

Verify that the API returns an error message if the request is malformed.

Language: Java

Framework: Rest assured

copy
1/​/​ Assumptions:2/​/​ - The API endpoint is http:/​/​example.com/​api.3/​/​ - The malformed request is a GET request without any query parameters.4/​/​ - The error message returned by the API is in JSON format and contains a "message" field.56import org.testng.annotations.Test;7import static io.restassured.RestAssured.*;8import static org.hamcrest.Matchers.*;910public class MalformedRequestTest {1112 @Test13 public void testMalformedRequest() {14 given()15 .when()16 .get("http:/​/​example.com/​api")17 .then()18 .statusCode(400)19 .body("message", equalTo("Bad Request"));20 }2122 /​/​ Uncomment the code below to use a remote client with desired capabilities.23 /​/​ public void setUp() {24 /​/​ DesiredCapabilities capabilities = new DesiredCapabilities();25 /​/​ /​/​ Set desired capabilities here.26 /​/​ RemoteWebDriver driver = new RemoteWebDriver(new URL("http:/​/​localhost:4444/​wd/​hub"), capabilities);27 /​/​ RestAssured.config = RestAssured.config().httpClient(HttpClientConfig.httpClientConfig().replaceWebDriver(driver));28 /​/​ }29}

Language: Javascript

copy
1/​/​ Mocha + Chai234const request = require('superagent');5const expect = require('chai').expect;67describe('API Testing', function() {8 it('Check malformed request', async function() {9 const endpoint = '<API Endpoint>'; /​/​ Replace with actual API endpoint10 const malformedRequest = {11 /​/​ Add malformed request payload here12 };13 const expectedErrorMessage = 'Invalid request format'; /​/​ Replace with expected error message14 15 const response = await request.post(endpoint).send(malformedRequest);16 17 expect(response.status).to.equal(400);18 expect(response.body.errorMessage).to.equal(expectedErrorMessage);19 });20});

Disclaimer: Following code snippets and related information have been sourced from GitHub and/or generated using AI code generation tools. LambdaTest takes no responsibility in the accuracy of the code and is not liable for any damages.

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Power Your Software Testing with AI and cloud

Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.

Start Free Testing