API Negative Testing in Cucumber with REST Assured
What Is API Negative Testing?
API negative testing is the process of verifying how an API behaves when it receives invalid, unexpected, incomplete, unauthorized, malformed, or business-rule-breaking requests. Positive testing confirms that an API works correctly with valid input. Negative testing confirms that the same API fails correctly when the input or request condition is wrong. A strong API is not defined only by how it succeeds. It is also defined by how safely, predictably, and consistently it rejects bad requests.
In Cucumber with REST Assured, negative testing is written as readable Gherkin scenarios and implemented through Java API clients, request builders, REST Assured calls, response validators, and error schema checks. The feature file explains the invalid condition, such as wrong password, missing email, invalid token, unsupported media type, duplicate customer, or forbidden admin operation. REST Assured sends the actual invalid request and validates the response.
In simple terms, API negative testing verifies that an API fails correctly and safely when invalid data or invalid requests are sent. The API should reject invalid requests, return appropriate error codes, provide meaningful error messages, avoid exposing sensitive information, and remain stable under invalid conditions. It should not crash, store bad data, bypass rules, or return vague errors that make client handling difficult.
Why Negative Testing Is Important
A secure and reliable API should not accept every request. Real users, client applications, integration partners, scripts, and malicious actors can send bad input. Some bad input is accidental, such as missing fields or wrong formats. Some is intentional, such as SQL injection, XSS payloads, token manipulation, or repeated requests. The API must validate input and respond safely.
Client
-> Invalid request
-> API validation
-> Reject request
-> Return proper error
Without negative testing, invalid data may be stored in the system, security vulnerabilities may exist, unexpected server crashes may occur, and business rules may be bypassed. For example, if a payment API accepts a negative amount, a financial defect may result. If a user API accepts duplicate email addresses, login and account ownership may become unreliable. If an admin API allows a normal user to perform restricted actions, the issue becomes a security defect.
Negative testing also improves API usability. Client developers need predictable error responses. If one validation failure returns 400 with a clear error body but another returns 500 with a stack trace, client handling becomes difficult. A consistent error contract helps API consumers build better applications.
Positive vs Negative Testing
Positive testing uses valid input and expects success. Negative testing uses invalid input or invalid conditions and expects failure. Both are necessary. Positive tests prove the happy path. Negative tests prove validation, security, and error handling. A test suite that only checks successful 2xx responses is incomplete.
| Positive Testing | Negative Testing |
|---|---|
| Uses valid input | Uses invalid input |
| Expects success | Expects failure |
| Validates correct behavior | Validates error handling |
| Usually returns 2xx status | Usually returns 4xx or sometimes 5xx status |
For example, valid login with the correct username and password should return 200 OK and a token. Login with a wrong password should return 401 Unauthorized or another documented authentication error. The negative scenario is not less important. It proves that an attacker or mistaken user cannot authenticate with invalid credentials.
Negative Testing Flow
The negative testing flow starts by intentionally building an invalid request. The request may contain missing fields, invalid values, wrong data types, malformed JSON, missing authentication, invalid headers, unsupported methods, or business-rule violations. REST Assured sends the request. The API validates the input and rejects it. The response validator checks status code, error body, error code, message, schema, and any business-specific error details.
Build invalid request
-> Send request
-> API validates input
-> Reject request
-> Return error response
-> Validate error
This flow should be deliberate. A negative test should fail for the intended reason. If a missing-email test fails because authentication was missing, the test is not validating the intended rule. Clean request builders, good setup, and focused scenarios help prevent misleading failures.
Types of API Negative Testing
Negative testing covers many categories. It includes invalid input, missing required fields, invalid data types, empty values, null values, boundary violations, duplicate data, invalid authentication, missing authentication, expired tokens, forbidden access, invalid endpoints, invalid HTTP methods, invalid headers, malformed JSON, business rule violations, security payloads, and server error handling.
Negative Testing
Invalid Input
Missing Fields
Invalid Data Type
Boundary Violations
Unauthorized Access
Forbidden Access
Invalid Endpoint
Invalid HTTP Method
Invalid Headers
Malformed JSON
Duplicate Data
Business Rule Violations
Security Inputs
Each category tests a different part of API robustness. Invalid input tests validation rules. Authentication tests identity. Authorization tests permission. Invalid method tests endpoint contract. Malformed JSON tests parsing behavior. Security inputs test whether the API safely handles malicious content. A mature API suite includes representative coverage from all relevant categories.
Invalid Input Testing
Invalid input testing verifies that the API rejects values that do not satisfy the contract. For example, if age must be positive, sending age as -5 should fail. If quantity must be at least 1, sending 0 should fail. If username must not contain special characters, sending invalid characters should produce a validation error.
{
"age": -5
}
The expected response is usually 400 Bad Request or a documented validation status. The test should validate not only the status code but also the error body. The error should explain which field failed and why. Good error responses make API consumers more productive.
Missing Required Fields
Missing required fields are one of the most common negative API cases. If the API requires name and email, sending only name should fail. This validates server-side rules. Client-side validation is helpful, but APIs must never rely only on clients to enforce required fields.
{
"name": "John"
}
The expected response may be 400 Bad Request, 422 Unprocessable Entity, or another documented validation response. The exact status code depends on the API specification. The important point is that the API should reject the request predictably and should not create partial or invalid data.
Invalid Data Types
Invalid data type testing verifies that the API rejects fields with the wrong JSON type. If age is expected to be a number, sending "twenty five" as a string should fail. If active is expected to be Boolean, sending "true" as a string may be invalid depending on the contract. Type validation protects downstream logic from unsafe assumptions.
{
"age": "twenty five"
}
These defects often occur when clients send loosely typed data or when APIs accept input too permissively. A robust API validates types before processing business logic. REST Assured negative tests can send deliberately wrong types through raw JSON payloads or flexible maps.
Empty Values
Empty values are different from missing fields. A field may be present but contain an empty string. If name is mandatory, "name": "" should usually fail. Some APIs accidentally accept empty strings because they validate only field presence, not actual content. Negative testing catches this gap.
{
"name": ""
}
Empty arrays and empty objects also deserve attention. If an order must contain at least one item, an empty items array should be rejected. If an address object is required, an empty object may not be enough. Tests should reflect the business rule, not just JSON shape.
Null Values
Null value testing checks how the API handles fields explicitly set to null. A required email field with null should usually fail. However, some optional fields may legitimately allow null. The expected result depends on the API contract. This is why null behavior should be clearly defined.
{
"email": null
}
Null handling defects can cause server-side exceptions if the code assumes a field is always present. A good API validates null values and returns controlled errors. It should not throw unhandled exceptions or expose stack traces.
Boundary Value Testing
Boundary value testing checks limits. If minimum age is 18, test 17, 18, and 19. If maximum length is 50 characters, test 49, 50, and 51. APIs frequently fail around boundaries because developers implement greater-than and greater-than-or-equal rules incorrectly.
Minimum age: 18
Test values: 17, 18, 19
Boundary testing is not only negative. It includes just-below, exact, and just-above values. The invalid side should be rejected, while the valid boundary should be accepted. This gives confidence that the rule is implemented precisely.
Duplicate Data
Duplicate data testing verifies uniqueness rules. If email must be unique, creating a customer with the same email twice should fail on the second request. The expected response may be 409 Conflict or another documented duplicate-resource error.
Create customer with john@test.com
Create customer again with john@test.com
Expected: duplicate error
Duplicate tests require careful setup. The first record must exist before the duplicate request is sent. The test should also clean up created data when appropriate. If cleanup is not possible, use generated emails with a clear test prefix so records can be identified later.
Invalid Authentication
Invalid authentication testing verifies that the API rejects bad credentials or invalid tokens. A request with a malformed bearer token, fake token, revoked token, or incorrect API key should not access protected resources. The typical response is 401 Unauthorized, but the exact behavior should follow the API specification.
Authorization: Bearer invalid-token
The response should not reveal sensitive implementation details. It should not say whether a username exists unless the product intentionally allows that. It should not expose stack traces, internal service names, or token parsing details. Negative authentication tests support both quality and security.
Missing Authentication
Missing authentication testing sends a request to a protected endpoint without credentials. If the endpoint requires authentication, the API should reject the request. This catches accidental exposure of secured resources.
No Authorization header
Expected: 401 Unauthorized
This test is simple but important. A protected endpoint that works without authentication is a serious defect. Every secured API module should include missing-authentication coverage for critical endpoints.
Expired Token
Expired token testing verifies that the API rejects tokens that were once valid but are no longer usable. Token expiry is a normal part of secure API design. The API should detect expired tokens and return a controlled authentication failure.
Authorization: Bearer expired-token
Expected: 401 Unauthorized
Testing expired tokens may require a generated short-lived token, a test identity provider, or a controlled token fixture. The framework should avoid relying on real long-lived tokens. Expired-token scenarios are useful because they validate real-world session and security behavior.
Forbidden Access
Forbidden access tests verify authorization. Authentication succeeded, but the authenticated client is not allowed to perform the operation. For example, a normal user attempts an admin action, a read-only token attempts an update, or a support user attempts a finance-only operation. The expected response is usually 403 Forbidden.
Authenticated user
-> Attempts admin operation
-> Expected: 403 Forbidden
These tests are critical because permission defects can expose data or allow unauthorized changes. Feature files should use business language, such as "a support user cannot approve refunds." The Java layer can handle the token and endpoint details.
Invalid Endpoint
Invalid endpoint testing calls an endpoint that does not exist. The API should return 404 Not Found or a documented routing error. This confirms that unknown paths are handled cleanly.
GET /api/unknownEndpoint
Expected: 404 Not Found
Invalid endpoint tests are useful for gateway and routing behavior. They should not dominate the suite, but they are helpful for proving that unknown resources return consistent error responses.
Invalid HTTP Method
Invalid HTTP method testing sends a method that the endpoint does not support. If login supports only POST, sending DELETE to the login endpoint should not succeed. The expected response is often 405 Method Not Allowed.
DELETE /login
Expected: 405 Method Not Allowed
These tests validate the API contract. They also help catch accidental route configurations where unsupported methods are accepted. REST Assured makes method variation straightforward.
Invalid Headers
Invalid header testing verifies that the API handles incorrect or missing metadata correctly. If an endpoint expects JSON and the client sends Content-Type: text/plain, the API may return 415 Unsupported Media Type. If the Accept header requests an unsupported format, the API may return 406 Not Acceptable depending on the implementation.
Content-Type: text/plain
Expected: 415 Unsupported Media Type
Header tests are important because request metadata affects parsing and response formatting. A malformed body may not even reach business validation if Content-Type is wrong. Good troubleshooting separates header failures from payload failures.
Malformed JSON
Malformed JSON testing sends syntactically invalid JSON. For example, a request body may miss a closing brace, contain invalid commas, or use broken string quoting. The API should reject the request with a controlled bad-request response. It should not crash or expose parser stack traces.
{
"name": "John"
Malformed JSON tests are often implemented with raw string payloads because POJO serialization normally produces valid JSON. They are useful for validating request parsing and error handling at the API boundary.
Business Rule Validation
Business rule negative testing verifies that the API does not allow actions that violate product rules. For example, a user cannot withdraw more money than available balance, an inactive customer cannot place an order, a cancelled order cannot be shipped, and an employee cannot approve their own request. These are not just data-format errors; they are business protections.
Withdraw amount: 10000
Available balance: 500
Expected: business validation error
Business rule scenarios should be written in domain language. The feature file should explain the rule. The validator should check the documented status code and error body. These tests often catch high-value defects because they validate real product behavior.
SQL Injection Testing
SQL injection testing sends input that attempts to manipulate database queries, such as ' OR 1=1 --. Modern applications should use parameterized queries and validation so such input does not expose data, bypass authentication, or crash the server. The expected behavior depends on the API, but it should be safe and controlled.
' OR 1=1 --
API automation can include basic malicious input checks, but deep security testing may require dedicated security tools and expert review. Still, adding representative injection payloads to critical APIs helps catch obvious vulnerabilities and unsafe error exposure.
XSS Testing
XSS testing sends script-like input, such as <script>alert('XSS')</script>. APIs that store and later display user input should handle this safely. Depending on the application, the API may reject the input, encode it, sanitize it, or store it safely for later rendering. The expected behavior should be defined by security requirements.
<script>alert('XSS')</script>
REST Assured can send these payloads like any other data. Validation may include checking that the API rejects the input or that the stored value is safely transformed. Avoid assuming one behavior without a requirement. Security-related negative tests should align with the product's security policy.
Error Response Validation
Negative tests should validate the error response body, not only the status code. A useful error response may include an error code, message, timestamp, path, request ID, trace ID, and field-level validation details. These values help API consumers understand what went wrong.
response.then()
.statusCode(400)
.body("error", equalTo("Invalid Request"));
Error messages should be meaningful but safe. They should explain the client-facing problem without exposing passwords, tokens, SQL queries, stack traces, internal class names, or infrastructure details. Negative tests can catch unsafe error exposure.
Error Schema Validation
Error schema validation confirms that error responses follow a consistent contract. This is useful across 400, 401, 403, 404, 405, 409, 415, 422, 429, and 500-level responses. A standard error schema makes client-side error handling easier.
response.then()
.body(matchesJsonSchemaInClasspath("schemas/error-schema.json"));
Error schema validation should be combined with specific value checks. The schema proves the structure. The value assertions prove that the correct error code and message were returned for the scenario. Both are needed for strong negative testing.
Negative Testing in Cucumber
Cucumber negative scenarios should remain business-readable. They should describe the invalid condition and expected rejection clearly. A scenario can say that login with an invalid password is rejected, a customer without email is not created, or a normal user cannot perform an admin operation.
Scenario: Login with invalid password
When the client logs in with username "admin"
And password "wrong"
Then the response status should be 401
And the response should contain "Invalid credentials"
This scenario is readable and focused. It does not expose all REST Assured details. The step definition builds the request, sends it, stores the response, and calls validators. The feature file documents behavior.
REST Assured Example
REST Assured makes negative testing straightforward. The framework can send an invalid request body and assert the expected error response. In real projects, this code is usually placed in API client and validator classes instead of being repeated inside step definitions.
Response response =
given()
.contentType(ContentType.JSON)
.body(request)
.when()
.post("/login");
response.then()
.statusCode(401)
.body("message", equalTo("Invalid credentials"));
The same pattern works for missing fields, invalid types, invalid headers, duplicate data, and business-rule failures. The request changes, the expected response changes, but the framework structure stays consistent.
Common HTTP Status Codes
Negative API tests commonly validate 4xx and sometimes 5xx status codes. The exact status code depends on the API specification. Do not assume every error should be 400. Authentication, authorization, missing resources, conflicts, unsupported media types, and rate limits all have different meanings.
| Status | Meaning |
|---|---|
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 405 | Method Not Allowed |
| 409 | Conflict |
| 415 | Unsupported Media Type |
| 422 | Unprocessable Entity |
| 429 | Too Many Requests |
| 500 | Internal Server Error |
Status code expectations should come from the API contract. If the contract says duplicate email returns 409, validate 409. If validation errors use 422, validate 422. Consistency is more important than personal preference.
Designing Negative Test Data
Negative test data should be intentional. Each invalid value should exist because it tests a specific rule. A dataset should explain whether it is testing missing data, invalid format, boundary violation, duplicate state, security input, or permission failure. This makes failures easier to understand in reports.
For data-driven negative testing, include columns such as caseName, invalidField, inputValue, expectedStatus, expectedErrorCode, and expectedMessage. Clear data design prevents confusion when many negative rows execute through one Scenario Outline or external file.
Verifying System State After Negative Tests
Some negative tests should verify that invalid requests did not change system state. For example, a failed create-customer request should not create a partial customer. A failed payment should not mark an order as paid. A forbidden update should not modify the resource. This kind of validation is important because an API may return an error but still perform part of the operation incorrectly.
State verification can be done by retrieving the resource after the failed request, checking audit records, or querying a controlled test database when appropriate. Use this level of validation for high-risk business operations where partial updates would be serious.
Rate Limit and Too Many Requests Testing
Rate limiting protects APIs from excessive traffic. Negative testing may include verifying that too many requests are rejected with 429 Too Many Requests and that the response includes useful retry information when the API contract defines it. This is especially relevant for public APIs, authentication endpoints, and payment or search services.
Rate-limit tests should be isolated and used carefully because they can affect shared environments. They may need special test accounts or lower configured limits. Do not run aggressive rate-limit tests in every smoke suite unless the environment is designed for it.
Common Mistakes
The first common mistake is testing only happy paths. A suite full of 200 OK and 201 Created checks does not prove that the API is safe. Another mistake is ignoring the error body and checking only statusCode(400). Always validate error message, error code, business meaning, and schema when applicable.
Teams also sometimes think negative testing means only invalid credentials. Negative testing is much broader. It includes missing fields, invalid data, invalid methods, invalid endpoints, boundary values, authorization rules, invalid headers, malformed payloads, duplicate data, and security-related inputs. Another mistake is assuming every error should be 400. Follow the API specification.
Skipping cleanup is also risky. Some negative tests may create partial data if the API has a defect. The framework should verify state and clean up when necessary. Otherwise, failed negative tests can pollute the environment and affect later runs.
Best Practices
Include negative scenarios for every important API endpoint. Validate both HTTP status codes and error response bodies. Test missing, null, invalid, duplicate, and boundary inputs. Validate authentication and authorization failures. Validate malformed JSON and incorrect headers. Use error schema validation for consistent error contracts. Verify that business rules cannot be bypassed.
Automate negative tests as part of regression suites. Use Scenario Outlines or external data for repeated invalid combinations. Keep Gherkin readable by describing the invalid behavior instead of low-level HTTP mechanics. Centralize error validation in reusable validator classes. Mask sensitive data in logs and reports. Keep negative data clear and purposeful.
Enterprise Framework Architecture
In an enterprise Cucumber REST Assured framework, negative testing follows the same layered architecture as positive testing. The feature file describes the invalid behavior. The step definition calls an API client. The request builder prepares an invalid request. REST Assured sends it. The API returns an error response. The error validator checks status, body, schema, and business meaning. Reports show the failure behavior clearly.
Feature File
-> Step Definition
-> API Client
-> REST Assured
-> Invalid Request
-> API
-> Error Response
-> Error Validator
-> Report
This separation makes negative tests maintainable. Request builders can create invalid payloads intentionally. Error validators can be reused across endpoints. Scenario context can store IDs for setup and cleanup. Reports can show exactly which invalid condition was tested.
Negative Test Categories
| Category | Example |
|---|---|
| Invalid Input | Wrong data value |
| Missing Fields | Required field omitted |
| Invalid Type | String instead of integer |
| Boundary Values | Length or range limits |
| Authentication | Invalid or missing token |
| Authorization | Forbidden resource |
| Endpoint | Invalid URL |
| HTTP Method | Unsupported method |
| Headers | Wrong Content-Type |
| Payload | Malformed JSON |
| Business Rules | Duplicate or invalid business action |
| Security | SQL injection or XSS-like input |
This table is a practical checklist. Not every endpoint needs every category, but critical APIs should be reviewed against each one. The highest-risk operations usually deserve the broadest negative coverage.
Real-Time Example
Consider an order creation API. Positive testing confirms that a valid customer can place an order with valid items and payment details. Negative testing checks that an unauthenticated client cannot place an order, an inactive customer cannot place an order, an empty item list is rejected, negative quantity is rejected, invalid product ID is rejected, duplicate idempotency key is handled correctly, and insufficient payment balance prevents order completion.
A strong framework uses request builders to create a valid order first, then changes one field at a time for each negative case. Validators check the expected status code, error code, message, and error schema. For high-risk cases, the test also retrieves the order or customer afterward to prove that no invalid state was created. This gives confidence that the API rejects bad requests safely.
Designing Negative Scenario Outlines
Scenario Outlines are useful for negative API testing when the workflow is the same and only the invalid data changes. For example, a customer creation API may reject missing email, invalid email format, blank name, long phone number, and invalid date of birth through the same create-customer request. A Scenario Outline can hold the invalid field, invalid value, expected status, and expected error code.
The outline should remain readable. If the table grows too large or starts mixing unrelated rules, split it. A small outline for customer field validation is useful. A giant outline that mixes authentication errors, payload errors, duplicate errors, and authorization errors becomes difficult to understand. Group negative data by behavior category so reports remain meaningful.
Prioritizing Negative Test Coverage
Not every endpoint needs the same amount of negative testing. Risk should guide coverage. Authentication, payment, user management, authorization, account updates, order processing, file upload, and personally identifiable data endpoints deserve deeper negative coverage. Low-risk read-only endpoints may need fewer cases, but they still need basic error handling validation.
Start with required fields, invalid types, authentication, authorization, and business rules. Then add boundary values, duplicate data, malformed JSON, invalid methods, and security-oriented inputs. This staged approach builds useful coverage quickly and prevents the suite from becoming bloated with low-value cases before critical risks are covered.
Negative Testing and API Documentation
Good negative tests should align with API documentation. The documentation should explain which status codes and error bodies are expected for invalid input, unauthorized access, forbidden operations, duplicate records, unsupported media types, and missing resources. If the documentation is unclear, negative testing often exposes that gap.
When an API returns different error formats for similar failures, teams should discuss whether the behavior is intentional. Automation can enforce the agreed contract after it is clarified. In this way, negative testing improves not only software quality but also API documentation quality. Clear error contracts help both internal teams and external consumers.
Debugging Negative Test Failures
When a negative test fails, first confirm that the test sent the intended invalid condition. A missing-email test should actually omit email. An invalid-token test should send an invalid token. A forbidden-access test should use a valid token for the wrong role. If the request is not built correctly, the failure does not prove anything about the API.
Next, compare the actual response with the documented expectation. If the API returns 500 instead of 400, it may be failing unsafely. If it returns 200 for invalid data, validation may be missing. If it returns the right status but the wrong error body, the contract may be inconsistent. Good logs and readable reports make this analysis much faster.
Interview-Ready Summary
API negative testing verifies that an API correctly rejects invalid requests and handles errors safely. Negative tests cover invalid inputs, missing fields, incorrect data types, empty values, null values, boundary violations, authentication failures, authorization failures, malformed payloads, invalid headers, invalid endpoints, unsupported methods, duplicate data, business rule violations, and security-related inputs.
REST Assured validates error responses using status codes, response bodies, JsonPath, Hamcrest matchers, and JSON Schema validation. In Cucumber, negative scenarios should be business-readable and focused. Enterprise API frameworks include both positive and negative tests in every regression suite because reliable APIs must succeed correctly and fail safely.
Golden Rules
Every positive API test should have corresponding negative tests. Validate error messages and business rules, not just HTTP status codes. Test invalid inputs, authentication, authorization, headers, payloads, endpoints, methods, duplicate data, boundaries, and security inputs. Use schema validation for error responses as well as successful responses. Ensure APIs fail securely, predictably, and according to their documented contract.
The practical takeaway is simple: negative testing proves that bad requests cannot damage the system, bypass rules, expose sensitive information, or produce confusing errors. That is why it is a core part of serious Cucumber and REST Assured API automation.