Negative Testing

Introduction

Real-world users and systems do not always send perfect requests. APIs receive missing fields, wrong data types, expired tokens, invalid IDs, malformed JSON, unsupported HTTP methods, oversized payloads, duplicate requests, invalid business values, and sometimes intentionally malicious input. A strong API must handle these situations safely. It should not crash, expose internal details, bypass security, corrupt data, or return confusing responses. It should reject invalid requests clearly and keep the application stable.

Negative Testing verifies that an API behaves correctly when it receives invalid, unexpected, unauthorized, or malicious input. Instead of checking only the happy path, it asks what happens when the request is wrong, incomplete, forbidden, malformed, or harmful. The expected result is not success. The expected result is controlled rejection with the correct status code, useful error response, safe logging, and no leakage of sensitive implementation details.

In API testing, Negative Testing is just as important as Positive Testing. Positive Testing proves that valid workflows work. Negative Testing proves that invalid workflows are handled safely. An API that creates an employee with valid data is useful, but it also must reject missing names, invalid salaries, unauthorized callers, duplicate identities, SQL injection payloads, and unexpected JSON properties. Without Negative Testing, teams may release APIs that work for normal users but fail under realistic error conditions.

Negative Testing improves robustness, stability, security, and user experience. It helps testers discover validation gaps, broken authorization, unsafe error messages, weak authentication handling, missing business rule checks, unhandled exceptions, and security vulnerabilities. It is one of the most practical ways to evaluate whether an API is ready for real traffic.

What Is Negative Testing?

Negative Testing is a testing technique that verifies an application behaves correctly when invalid, unexpected, unauthorized, or malicious input is provided. In API testing, it means sending requests that should not be accepted and confirming that the API rejects them safely.

A simple definition is this: Negative Testing checks whether the API properly handles invalid requests, incorrect data, and error conditions without crashing or exposing sensitive information. The goal is not to make the API succeed. The goal is to make sure the API fails correctly.

For example, if an employee creation API requires a `name` field, a negative test sends a request without `name` and expects a validation error such as `400 Bad Request`. If a protected endpoint requires a valid token, a negative test sends no token, an invalid token, or an expired token and expects `401 Unauthorized`. If an employee tries to call an admin-only delete endpoint, the expected response is `403 Forbidden`.

Negative Testing is not random testing. It should be based on API contracts, business rules, security requirements, data validation rules, authentication rules, authorization rules, and known attack patterns. Good negative tests are intentional, repeatable, and tied to expected failure behavior.

Why Negative Testing Is Important

Negative Testing verifies error handling. Every API will eventually receive invalid requests, and the quality of the error response matters. A good API tells the client what went wrong without exposing database queries, stack traces, server paths, framework names, secrets, or internal architecture. This makes troubleshooting easier for legitimate clients while reducing useful information for attackers.

Negative Testing improves application stability. If malformed JSON, long strings, missing fields, invalid content types, or unsupported methods cause unhandled exceptions, the API is fragile. A stable API rejects such requests consistently and continues serving other users. Stability matters especially in public APIs, enterprise integrations, mobile backends, and high-traffic services.

Negative Testing also identifies security vulnerabilities. Many API security issues are discovered by trying requests that normal clients should not send. Broken authorization may appear when one user changes another user's ID in a path parameter. Mass assignment may appear when a client adds `role: admin` to a request body. Injection vulnerabilities may appear when special strings are sent in query parameters or JSON fields. Information disclosure may appear when errors reveal stack traces or SQL messages.

From a business perspective, Negative Testing protects workflows and data. It validates that business rules are enforced even when clients bypass the UI and call APIs directly. A user interface may prevent negative quantity, but the API must also reject it. A screen may hide admin actions, but the API must still enforce permissions. Negative Testing confirms that backend rules cannot be bypassed by direct API access.

Negative Testing Workflow

A typical Negative Testing workflow starts with an invalid request. The invalid condition may be related to input, authentication, authorization, business rules, content type, request size, or security payloads. The API validates the request, rejects it, returns a proper error response, and remains stable.

Invalid Request
  |
API Validation
  |
Request Rejected
  |
Proper Error Response
  |
Application Remains Stable

This workflow is important because a negative test is successful only when the API fails safely. If the API returns a generic `500 Internal Server Error` for ordinary validation issues, that usually indicates poor handling. If it returns `200 OK` for an invalid request, that is worse because the API may have accepted bad data. If it returns a stack trace, database error, or token details, it may create a security risk.

After the response is returned, testers should also verify side effects. An invalid create request should not insert partial data. An unauthorized delete request should not remove records. A malformed update should not change existing values. A failed payment request should not capture money. Negative Testing must confirm both the error response and the unchanged system state.

Characteristics of Negative Testing

Negative Testing uses invalid input, missing fields, wrong data types, unauthorized access, expired tokens, invalid HTTP methods, malformed JSON, boundary violations, and security attack payloads. The expected outcome is that the API safely rejects the request.

Invalid input may include values that are syntactically wrong, semantically wrong, or unacceptable for business reasons. An email such as `abc@` may be syntactically invalid. A salary value of `"ABC"` is the wrong data type. A transfer amount of `-500` may be syntactically numeric but invalid by business rule. Negative Testing should include all of these categories.

Authentication failures validate identity checks. These include missing tokens, invalid tokens, expired tokens, revoked tokens, malformed bearer headers, and tokens signed with the wrong key. Authorization failures validate permission checks. These include insufficient roles, accessing another user's resource, admin endpoint access by non-admin users, and horizontal privilege escalation attempts.

Security attack payloads are also part of Negative Testing. SQL injection strings, NoSQL injection payloads, XSS snippets, command injection attempts, path traversal patterns, unexpected JSON properties, and header manipulation should be handled safely. The API should not execute malicious input, expose internal errors, or accept unauthorized changes.

Invalid Login Example

A common negative test is login with a wrong password. The request may have a valid structure, but the credentials are incorrect. The API should reject the request with an authentication failure response.

POST /login
Content-Type: application/json

{
  "username": "john",
  "password": "WrongPassword"
}

The expected result is usually `401 Unauthorized`. The response should not reveal whether the username exists or whether only the password is wrong unless the business has intentionally accepted that risk. A safer response is a generic authentication failure message.

This test helps verify that invalid credentials cannot produce a token. Testers should also confirm that the response does not include access tokens, refresh tokens, password hashes, user secrets, stack traces, or overly detailed authentication logic.

Missing Required Field Example

A missing required field is one of the most basic and important negative tests. If an employee creation API requires `name`, a request without `name` should be rejected.

POST /employees
Content-Type: application/json

{
  "department": "QA"
}

The expected response is commonly `400 Bad Request`, although some APIs use `422 Unprocessable Entity` for validation errors. The response should clearly identify the validation problem without exposing internal implementation details.

400 Bad Request

{
  "message": "Name is required"
}

The tester should verify that no employee record was created. If the database contains a partial record with missing name, the API has a data integrity defect even if it returned an error response. Negative tests must verify that invalid requests do not damage backend state.

Invalid Data Type Example

Wrong data type testing verifies whether the API validates the structure and types of request fields. If salary must be numeric, sending a string such as `"ABC"` should be rejected.

{
  "name": "John",
  "department": "QA",
  "salary": "ABC"
}

The expected response is usually `400 Bad Request` or `422 Unprocessable Entity`, depending on the API standard. The API should not attempt unsafe conversion, save incorrect data, or return an unhandled exception.

This test is especially important for APIs that receive JSON from multiple clients. JavaScript, mobile apps, integrations, and external systems may send unexpected data types. The backend must validate the request independently instead of assuming the client did everything correctly.

Invalid and Expired JWT Examples

Authentication-related negative tests are critical for protected APIs. A request with an invalid token should be rejected. A request with an expired token should also be rejected. If revoked tokens are supported, revoked tokens should not work either.

GET /employees/101
Authorization: Bearer invalidToken

The expected result is `401 Unauthorized`. The response should not expose token parsing details, signing keys, algorithm decisions, or internal security library errors. It should simply communicate that authentication failed.

For expired JWTs, the API should reject the request even if the token was valid in the past. This verifies that expiry checks are enforced server-side. If refresh tokens are part of the design, the access endpoint should reject the expired access token, while the token renewal endpoint should follow the separate refresh-token rules.

Unauthorized Access Example

Authorization testing verifies whether an authenticated user is allowed to perform the requested action. A user may be logged in and still not have permission. For example, an employee user may try to delete another employee record through an admin-only endpoint.

DELETE /employees/101
Authorization: Bearer employeeToken

The expected response is `403 Forbidden`. The API should not delete the employee. The tester should verify the response and also confirm that employee `101` still exists. Authorization failures are among the most important negative tests because broken authorization can expose or modify sensitive data.

Authorization negative tests should include vertical privilege escalation and horizontal privilege escalation. Vertical escalation means a lower-privilege user attempts an admin action. Horizontal escalation means User A tries to access or modify User B's resource.

Resource Not Found and Invalid Method Examples

A request for a non-existing resource should be handled cleanly. If `GET /employees/999999` refers to no employee, the expected response is usually `404 Not Found`. The response should not crash or expose database lookup details.

Unsupported HTTP methods should also be tested. If an endpoint does not support `TRACE`, `PATCH`, or another method, the expected response is commonly `405 Method Not Allowed`. For example, `PATCH /login` may be unsupported if login only accepts `POST`. Method handling is part of API contract validation and security hardening.

Invalid method testing is useful because some servers accidentally expose methods that should be disabled. Testers should verify that dangerous or unnecessary methods are not available unless explicitly required.

Malformed JSON and Injection Examples

Malformed JSON testing verifies whether the API handles invalid request syntax gracefully. A broken payload such as an unclosed JSON object should return a client error, not a server crash.

{
  "name": "John",

The expected result is `400 Bad Request`. The error should indicate invalid JSON or malformed request body without returning parser stack traces or framework internals.

Injection testing sends payloads such as `' OR '1'='1` in fields, query parameters, or path parameters. The API should reject or safely handle the input. It should not bypass authentication, alter SQL logic, expose database errors, or return unauthorized data.

{
  "username": "' OR '1'='1",
  "password": "anything"
}

Injection tests are security-focused negative tests. Even when the expected status code varies by API design, the key expectations remain the same: no unauthorized access, no unsafe execution, no internal error disclosure, and no data corruption.

Types of Negative Testing

Input validation testing checks missing fields, invalid formats, wrong data types, empty values, null values, special characters, overly long values, unsupported enum values, and unexpected JSON properties. These tests verify that the API enforces its request contract.

Authentication testing checks missing tokens, invalid tokens, expired tokens, revoked tokens, malformed authorization headers, wrong authentication schemes, and invalid credentials. These tests prove that identity is required and enforced.

Authorization testing checks insufficient permissions, role validation, resource ownership, admin endpoint access, and tenant isolation. These tests prove that authenticated users can perform only allowed actions.

Business rule validation checks application-specific rules such as negative quantity, future birth date, duplicate registration, invalid account status, insufficient balance, unavailable inventory, and invalid workflow state. These tests are often more valuable than generic validation because they protect actual business behavior.

Boundary value testing checks maximum length, minimum value, zero values, overflow values, exact limits, and values just outside the accepted range. Security testing checks SQL injection, NoSQL injection, XSS payloads, command injection, mass assignment, header manipulation, path traversal, and request smuggling where relevant.

Negative Testing in API Testing

QA engineers should verify error status codes, error messages, validation logic, input validation, authentication failures, authorization failures, business rule validation, security protections, API stability, and absence of sensitive information leakage. Each area adds confidence that the API handles invalid conditions predictably.

Error status codes should match the API specification. Validation failures may be `400 Bad Request` or `422 Unprocessable Entity`. Missing authentication should usually be `401 Unauthorized`. Insufficient permission should usually be `403 Forbidden`. Missing resources should usually be `404 Not Found`. Unsupported methods should usually be `405 Method Not Allowed`.

Error messages should be useful but safe. They should help legitimate clients fix requests, but they should not reveal SQL queries, stack traces, internal class names, server paths, tokens, secrets, or infrastructure details. Error response structure should be consistent across endpoints so clients can handle errors reliably.

API stability should be verified after invalid requests. The system should remain available, database state should remain correct, and future valid requests should continue to work. A negative test that crashes a service, breaks a session, locks a resource incorrectly, or corrupts data has found a serious defect.

Example Negative Test Cases

A missing required field test sends a request without a mandatory field and expects `400 Bad Request` or the documented validation status. An invalid email test sends a value such as `abc@` and expects validation failure. An invalid password test sends wrong credentials and expects `401 Unauthorized`. An expired JWT test sends an expired token and expects `401 Unauthorized`.

An unauthorized role test sends a valid request using a user that lacks permission and expects `403 Forbidden`. An invalid employee ID test requests a non-existing employee and expects `404 Not Found`. A SQL injection test sends malicious input and expects safe handling, no database error, and no unauthorized access. A very long input test sends a value exceeding the maximum length and expects validation failure without application crash.

These tests should also verify side effects. The missing required field test should not create records. The unauthorized role test should not modify data. The SQL injection test should not authenticate the user or return extra records. The large input test should not degrade the system or produce unsafe logs.

REST Assured Example

REST Assured can automate negative API tests in Java. A simple invalid data type test may send a string value for a numeric salary field and verify that the API returns a validation error.

given()
  .contentType("application/json")
  .body("""
  {
    "salary": "ABC"
  }
  """)
.when()
  .post("/employees")
.then()
  .statusCode(400);

In a stronger test, assertions should also validate the error response body, error code, field name, message, content type, and absence of sensitive information. If the endpoint could create data, the test may verify that no employee was created.

Postman Example

Postman is useful for exploring negative scenarios before automating them. Testers can send invalid tokens, missing headers, wrong HTTP methods, invalid JSON, SQL injection payloads, large request bodies, missing fields, invalid content types, and unexpected properties. Postman tests can assert status code, error response, headers, response time, and error structure.

For example, a Postman collection may include negative tests for employee creation: missing name, invalid salary type, empty department, extra `role` field, unsupported content type, and unauthorized token. These tests can be run manually during development or executed through Newman in a CI pipeline.

Postman environment variables are useful for tokens and test data, but testers should avoid storing real secrets in shared collections. Negative security tests should be designed responsibly and executed only in permitted test environments.

Karate Example

Karate allows negative API tests to be written in readable scenario form. A simple invalid salary test can define the request, call the endpoint, and assert the expected status.

Given request
"""
{
  "salary": "ABC"
}
"""
When method POST
Then status 400

Karate can also validate error response fields, reusable payloads, authentication setup, and data-driven examples. This makes it useful for negative validation matrices, where the same endpoint must reject many invalid inputs.

Real-World Examples

In banking, a negative test may attempt to transfer `-500`. The expected result is rejection because negative transfers should not be processed. The test should verify that balances remain unchanged and no transaction is recorded as successful.

In healthcare, a negative test may send patient age as `-10` or send a request for a patient record using an unauthorized role. The API should return a validation or authorization error and must not expose patient information. In healthcare systems, safe failure is especially important because of privacy and compliance requirements.

In e-commerce, a negative test may place an order with quantity `0`, unavailable inventory, invalid coupon code, unsupported payment method, or modified price field. The API should reject invalid business conditions and prevent users from manipulating order totals or inventory.

In employee management, a negative test may send salary as `ABC`, omit mandatory fields, use an expired token, or attempt deletion using a non-admin role. The expected result is controlled rejection with correct status and no data corruption.

Advantages of Negative Testing

Negative Testing finds hidden defects that positive tests cannot reveal. It improves application stability by ensuring invalid requests do not crash services. It validates error handling and confirms that clients receive meaningful responses. It identifies security weaknesses and prevents unexpected failures in production.

Negative Testing also improves API reliability. Real integrations are not always perfect. Network issues, client bugs, version mismatches, stale tokens, invalid data, and manual mistakes happen regularly. APIs that handle such problems gracefully are easier to support and safer to operate.

Another advantage is improved confidence in defensive design. When negative tests pass, teams know that validation, authentication, authorization, and error handling are not only documented but enforced. This helps reduce production incidents and security risks.

Limitations of Negative Testing

Negative Testing does not verify successful business workflows. It cannot replace Positive Testing. An API may reject invalid input correctly and still fail to process valid requests. Both directions are necessary for complete functional confidence.

Negative Testing can require many scenarios because invalid combinations are large. Each field may have missing, null, empty, wrong type, invalid format, too short, too long, boundary, special character, and malicious payload cases. Testers must prioritize based on risk, business criticality, API exposure, and past defects.

Complex business rules require extensive coverage. For example, payment, healthcare, insurance, taxation, banking, and access-control rules may include many invalid states. Test design should balance depth with maintainability so the suite remains useful instead of becoming noisy.

Positive Testing vs Negative Testing

Positive Testing uses valid input and expected workflows. Negative Testing uses invalid or unexpected input and error scenarios. Positive Testing expects a successful response. Negative Testing expects graceful rejection or controlled error handling. Positive Testing verifies functionality. Negative Testing verifies robustness, validation, and security behavior.

Positive TestingNegative Testing
Valid inputInvalid or unexpected input
Expected workflowError and failure scenarios
Successful responseGraceful rejection or error handling
Verifies functionalityVerifies robustness and security

A balanced API test strategy includes both. First confirm that valid behavior works. Then confirm that invalid behavior is rejected safely. This combination gives stronger confidence than either approach alone.

Best Practices

Test every important validation rule. Verify HTTP status codes, but do not stop there. Validate the error response structure, error message, field-level details, headers, and response time. Ensure messages are meaningful without exposing sensitive details. Test authentication and authorization failures thoroughly because they protect data and operations.

Include boundary value testing. If a field allows 1 to 100, test 0, 1, 100, and 101. If a field allows 50 characters, test exactly 50 and more than 50. Boundaries often reveal validation bugs. Include malicious payload testing for exposed fields, especially search, login, comments, filters, and free-text fields.

Verify that the application remains stable after invalid requests. Send a valid request after a negative request to confirm the service still behaves correctly. For write operations, verify that invalid requests do not create, update, or delete data. For security tests, verify that no unauthorized access occurred.

Automate important negative scenarios. Authentication, authorization, required fields, invalid data types, malformed JSON, and critical business rule failures are good regression candidates. Keep tests focused and readable so failures are easy to diagnose.

Common Mistakes

One common mistake is verifying only status codes. A `400` response is not enough if the error body is wrong, the field message is missing, sensitive details are exposed, or data was modified anyway. Always verify response body, error message, headers, and side effects where relevant.

Another mistake is ignoring security testing. Negative Testing should include injection attempts, authorization bypass attempts, malformed requests, suspicious headers, invalid tokens, and unexpected properties. Security defects often appear only when clients behave outside normal workflows.

Exposing internal errors is a serious mistake. Error responses should not reveal SQL queries, stack traces, file paths, server details, framework names, environment variables, token internals, or secrets. Negative tests should actively check for these leaks in error responses.

Testing only simple invalid data is also weak coverage. Test boundary values, large payloads, special characters, unexpected JSON properties, invalid content types, duplicate requests, unsupported methods, and application-specific business rules. Generic validation is useful, but business rule validation often finds the most important defects.

Common HTTP Status Codes

Negative API testing relies on status code expectations defined by the API specification. Different organizations may use slightly different standards, but common patterns are widely understood.

ScenarioStatus Code
Invalid request400 Bad Request
Missing or invalid authentication401 Unauthorized
Insufficient permission403 Forbidden
Resource not found404 Not Found
Unsupported method405 Method Not Allowed
Unsupported media type415 Unsupported Media Type
Validation error where used422 Unprocessable Entity
Rate limit exceeded429 Too Many Requests
Unexpected server failure500 Internal Server Error without implementation leakage

Some APIs use `400 Bad Request` for validation failures, while others use `422 Unprocessable Entity`. Follow the API specification being tested. The most important point is consistency. Clients should be able to handle errors predictably across endpoints.

Negative Testing Checklist

For each endpoint, ask what fields are required, what formats are allowed, what data types are expected, what values are out of range, what roles can access the endpoint, what resources belong to the caller, what methods are supported, what content types are accepted, and what business rules must be enforced.

Then design negative tests for missing fields, null values, empty values, wrong data types, invalid formats, boundary violations, non-existing IDs, unsupported methods, missing tokens, expired tokens, invalid tokens, unauthorized roles, resource ownership violations, duplicate requests, unexpected fields, injection payloads, malformed JSON, large payloads, and invalid content types.

For every negative test, verify the status code, error body, headers, absence of sensitive leakage, unchanged backend state, and continued API stability. A good negative test proves that the API rejected the request safely and predictably.

Interview Questions

A common interview question is: what is Negative Testing? A strong answer is that Negative Testing verifies that an API correctly handles invalid, unexpected, unauthorized, or malicious input without crashing or exposing sensitive information.

Another question is: why is Negative Testing important? The answer is that it validates robustness, security, error handling, and application stability. It ensures that APIs reject bad requests safely and enforce validation, authentication, authorization, and business rules.

Interviewers may ask what API testers should verify during Negative Testing. Good answers include input validation, authentication failures, authorization failures, business rule validation, error responses, security protections, application stability, and absence of sensitive information leakage.

If asked for an example, describe sending an employee creation request without the required `name` field and verifying that the API returns `400 Bad Request` with an appropriate validation message and does not create an employee record.

If asked whether Negative Testing can identify security issues, explain that it can uncover SQL injection, mass assignment, broken authorization, authentication weaknesses, malformed request handling, information disclosure, and other vulnerabilities. It is not a replacement for full security testing, but it is an important part of API security validation.

Interview-Ready Explanation

Negative Testing is a software testing technique used to verify that an API or application handles invalid, unexpected, unauthorized, or malicious input correctly. Instead of validating successful business workflows, it focuses on ensuring that the API rejects incorrect requests gracefully, returns appropriate HTTP status codes and error messages, enforces authentication and authorization rules, validates business constraints, and remains stable without exposing sensitive information or crashing.

In API testing, Negative Testing includes scenarios such as missing required fields, invalid data types, malformed JSON, expired or invalid tokens, unauthorized access attempts, boundary value violations, unsupported HTTP methods, invalid content types, oversized payloads, and security payloads like SQL injection. A good negative test also verifies that invalid requests do not create, update, delete, or expose data incorrectly.

Negative Testing is important because real clients and attackers do not always send valid requests. APIs must defend themselves at the backend level, even if the user interface prevents invalid actions. Together with Positive Testing, Negative Testing provides comprehensive validation of an API's functionality, robustness, stability, and security.

Key Takeaway

Negative Testing verifies that APIs fail safely. It checks whether invalid requests are rejected, error responses are meaningful, authentication and authorization are enforced, business rules are protected, security payloads are handled safely, and the application remains stable.

For practical API testing, do not treat Negative Testing as optional. Every important endpoint should be tested with valid requests and invalid requests. Positive Testing proves the API can do the right thing. Negative Testing proves the API refuses to do the wrong thing.