Verify that the API correctly handles field-level validation and returns the correct HTTP status code and error message.
Language: Java
Framework: Rest assured
1import static io.restassured.RestAssured.*;2import io.restassured.path.json.JsonPath;3import static org.hamcrest.Matchers.*;45public class APITestCase {6 public static void main(String[] args) {7 8 //Assumption: The API being tested requires authorization9 String accessToken = "someAccessToken";10 String baseURI = "https://example-api.com";11 int expectedStatusCode = 400;12 String expectedErrorMessage = "Invalid input";13 14 //Assumption: the field "name" is required15 String requestBody = "{ \"name\": \"\", \"age\": 30 }";16 17 given()18 .header("Authorization", "Bearer " + accessToken)19 .body(requestBody)20 .when()21 .post(baseURI + "/users")22 .then()23 .statusCode(expectedStatusCode)24 .body("message", equalTo(expectedErrorMessage));25 26 //Assumption: if the name field is filled in, the request is successful with status code 20027 String validRequestBody = "{ \"name\": \"John\", \"age\": 30 }";28 29 given()30 .header("Authorization", "Bearer " + accessToken)31 .body(validRequestBody)32 .when()33 .post(baseURI + "/users")34 .then()35 .statusCode(200)36 .body("name", equalTo("John"));37 38 //Assumption: the API can be tested remotely through a Selenium Grid39 //Uncomment the following code to connect to a remote client with desired capabilities40 41 /*42 DesiredCapabilities capabilities = new DesiredCapabilities();43 capabilities.setBrowserName("chrome");44 capabilities.setVersion("91");45 capabilities.setCapability("enableVNC", true);46 RemoteWebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capabilities);47 driver.get("https://example-api.com");48 */49 }50}
Language: Javascript
1// Mocha and Chai.23// Assumptions:4// - URL of API endpoint is known and stored in a variable 'apiUrl'5// - Field that requires validation is known and stored in a variable 'fieldName'6// - Expected HTTP status code is known and stored in a variable 'expectedStatusCode'7// - Expected error message is known and stored in a variable 'expectedErrorMessage'89const {expect} = require('chai');10const axios = require('axios');1112describe('API Testing - Field-level validation', () => {13 it('should correctly handle field-level validation', async () => {14 // Sample request payload15 const payload = {16 [fieldName]: 'invalid value'17 };1819 // Send request to API endpoint20 const response = await axios.post(apiUrl, payload);2122 // Assert response HTTP status code23 expect(response.status).to.equal(expectedStatusCode);2425 // Assert response error message26 const errorMessage = response.data.message.error;27 expect(errorMessage).to.equal(expectedErrorMessage);28 });29});3031// Uncomment the following code to run the test with remote client and desired capabilities3233// const webdriver = require('selenium-webdriver');34// const {Builder} = require("selenium-webdriver");35// const {Options} = require("selenium-webdriver/chrome");3637// const chromeOptions = new Options().addArguments("--headless");38// const capabilities = webdriver.Capabilities.chrome().set('chromeOptions', {39// 'args': ['--disable-infobars']40// });4142// const driver = new Builder()43// .withCapabilities(capabilities)44// .usingServer('http://localhost:4444/wd/hub')45// .build();4647// describe('API Testing - Field-level validation', () => {48// it('should correctly handle field-level validation', async () => {49// // Sample request payload50// const payload = {51// [fieldName]: 'invalid value'52// };5354// // Send request to API endpoint55// const response = await driver.executeScript(`56// return fetch('${apiUrl}', {57// method: 'POST',58// headers: {59// 'Content-Type': 'application/json'60// },61// body: JSON.stringify(${JSON.stringify(payload)})62// })63// .then(res => res.json())64// `);6566// // Assert response HTTP status code67// expect(response.status).to.equal(expectedStatusCode);6869// // Assert response error message70// const errorMessage = response.message.error;71// expect(errorMessage).to.equal(expectedErrorMessage);72// });73// });
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.
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.
Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.
Start Free Testing