1. Home
  2. Blog
  3. Software Testing

Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive testing checks that software works with valid input. Negative testing checks that it fails safely with invalid input, such as wrong types, empty fields and out-of-range values. See both applied to a real signup form, with 24 test cases we ran and the bug only a negative test caught.

9 min read
Positive vs negative testing with examples

Key takeaways

  • Positive vs negative testing: positive tests prove the happy path works; negative tests prove bad input is rejected safely.
  • Our signup form needed 6 positive tests and 18 negative ones; invalid inputs usually outnumber valid ones.
  • When we removed the maximum-age check, all 6 positive tests still passed. Only the negative test for age 121 failed.
  • A good negative test checks the specific error, not just “something failed”.

Most bugs that reach production are not in the happy path. Someone types a space into a username, pastes an email with no domain, or an API sends the number as text. Software that only works with perfect input fails in exactly those moments. Positive vs negative testing is the simplest way to think about covering both. To make it concrete, we wrote a small signup validator, designed 24 test cases, and ran them with pytest 9.2.0 on Python 3.13.

Quick answer

Positive testing uses valid input and checks that the system does what it should: the account is created, the payment succeeds, the report downloads. Negative testing uses invalid or unexpected input and checks that the system refuses it gracefully: a clear error, no crash, no corrupted data and no security hole. You need both; a requirement is only covered when its happy path and its failure paths are tested.

What is positive testing?

Positive testing, sometimes called happy-path testing, confirms that a feature works when used as intended. It answers “does it do what it promises?”. Examples: logging in with a correct password, searching for a product that exists, uploading a supported file type within the size limit. Positive tests come first, because if the main flow fails, nothing else matters.

What is negative testing?

Negative testing, sometimes called error-path testing, feeds the system input it should reject and checks the response. It answers “what happens when things go wrong?”. Examples: a wrong password, an empty required field, a 50 MB file when the limit is 10 MB, letters in a phone number, an expired session. A negative test passes when the system rejects the input correctly. It fails when the bad input is accepted, crashes the app or produces a confusing error.

A real example: the signup validator

Our requirements for a signup form:

  • Username: 3 to 20 characters, letters, digits and underscores only.
  • Age: a whole number from 18 to 120.
  • Email: something@domain.tld, no spaces.
  • Password: at least 8 characters, not letters only.
import re

def validate_signup(username, age, email, password):
    errors = []
    if not isinstance(username, str) or not re.fullmatch(r"[A-Za-z0-9_]{3,20}", username or ""):
        errors.append("username")
    if not isinstance(age, int) or not 18 <= age <= 120:
        errors.append("age")
    if not isinstance(email, str) or not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", email):
        errors.append("email")
    if not isinstance(password, str) or len(password) < 8 or password.isalpha():
        errors.append("password")
    return errors

The function returns a list of fields that failed. An empty list means the signup is valid. Returning field names, rather than true or false, lets each negative test check that the right field was rejected.

The 24 test cases

Field Positive (must be accepted) Negative (must be rejected)
Username “abc” (min), 20 letters (max) “ab”, 21 letters, “bad name”, empty, None
Age 18 (min), 120 (max) 17, 121, -1, “30” as text, True, 30.5
Email “a@b.co” “no-at-sign”, “a@b”, “a b@c.com”, empty
Password “abcdefg1” “short1”, “onlyletters”, None

That is 6 positive cases and 18 negative ones. The ratio is typical: there are usually a few ways to be right and many ways to be wrong. Notice that the positive cases sit exactly on the boundaries (3 and 20 characters, ages 18 and 120), and so do many negative ones (2, 21, 17, 121). Boundaries are where off-by-one bugs live; see our boundary value analysis guide.

The tests in pytest

import pytest
from signup import validate_signup

OK = dict(username="demo_user", age=30, email="demo@example.com", password="s3cretpass")

@pytest.mark.parametrize("field, value", [
    ("username", "abc"), ("username", "a" * 20), ("age", 18), ("age", 120),
    ("email", "a@b.co"), ("password", "abcdefg1"),
])
def test_positive(field, value):
    assert validate_signup(**{**OK, field: value}) == []

@pytest.mark.parametrize("field, value", [
    ("username", "ab"), ("username", "a" * 21), ("username", "bad name"),
    ("username", ""), ("username", None),
    ("age", 17), ("age", 121), ("age", -1), ("age", "30"), ("age", True), ("age", 30.5),
    ("email", "no-at-sign"), ("email", "a@b"), ("email", "a b@c.com"), ("email", ""),
    ("password", "short1"), ("password", "onlyletters"), ("password", None),
])
def test_negative(field, value):
    assert validate_signup(**{**OK, field: value}) == [field]
........................                     [100%]
24 passed in 0.10s

Each test starts from one known-good signup and changes exactly one field. That isolates the cause: if a negative test fails, you know which rule is broken. The == [field] assertion also confirms that no other field was wrongly rejected. Parametrize keeps 24 cases in two short functions; our pytest parametrize guide shows more patterns.

The bug only a negative test caught

To see the value of negative tests, we simulated a common developer mistake: checking only the minimum age. We changed one line to if not isinstance(age, int) or age < 18: and ran the suite again:

FAILED test_signup.py::test_negative[age-121] - AssertionError: assert [] == ['age']
1 failed, 23 passed in 0.19s

All six positive tests still passed, because the happy path still worked. An age of 121 was silently accepted, and only the negative boundary test noticed. Without it, the bug would have shipped. That is the core argument for negative testing: positive tests tell you the feature works, negative tests tell you its rules hold.

Tip: a quick way to judge a test suite is to break one validation rule and see whether any test fails. If nothing fails, you are missing a negative test.

Positive vs negative testing compared

Aspect Positive testing Negative testing
Input Valid, expected Invalid, unexpected or malicious
Question answered Does it work? Does it fail safely?
Passes when The action succeeds The input is rejected with the right error
Typical number of cases Fewer More
Finds Broken core features Missing validation, crashes, security gaps
Priority Run first Run right after, before release
Example Login with correct password Login with wrong password, empty password, SQL in the username

How to find negative test cases

  • Equivalence partitioning: split inputs into valid and invalid groups and test one value from each invalid group. See our equivalence partitioning guide.
  • Boundary values: test just outside each limit, such as 17 and 121.
  • Wrong types: text where a number belongs, a boolean, a decimal, null. Our test with "30" as text matters for APIs, where JSON numbers often arrive as strings.
  • Empty and missing: empty strings, whitespace only, missing fields.
  • Format breakers: spaces, emoji, very long input, special characters such as quotes and angle brackets.
  • State and sequence: submitting twice, using an expired link, acting after logout.

Generating varied input automatically helps too; our test data generation guide covers Faker and edge cases.

What a good negative test checks

“It did not crash” is not enough. A strong negative test checks that:

  1. The input is rejected, not silently accepted or “fixed”.
  2. The right rule triggered, with a clear message the user can act on.
  3. Nothing was saved or changed: no half-created account, no charge.
  4. The response is correct for an API, usually 400 or 422 rather than 500. Our HTTP status codes cheat sheet lists them.
  5. No sensitive details leak, such as stack traces or whether an email is registered.

Getting the balance right

Negative inputs are endless, so you cannot test them all. Prioritise by risk: validation that protects money, security and data integrity deserves the most negative cases, while a cosmetic field needs only a couple. A practical rule from many teams is at least one positive and one negative test per requirement, then more where failure is costly. Automate the stable ones at the unit or API level, where they run in milliseconds, and keep a few end-to-end checks for critical forms. Our risk-based testing guide shows how to rank features.

Positive and negative testing checklist

  • Every input has at least one positive and one negative case.
  • Both sides of every boundary are tested.
  • Wrong types, empty values and missing fields are covered.
  • Each negative test checks the specific error, not just failure.
  • Rejected requests change no data.
  • Error messages are clear and leak nothing sensitive.
  • API errors return 4xx codes, never 500.
  • New bugs found in production get a new negative test.

Final thoughts

Positive vs negative testing is not a choice between two techniques; it is two halves of the same job. Positive tests prove the feature works for the people using it correctly. Negative tests prove its rules survive everyone else. Our 24-case example showed the payoff in one line: when a validation rule broke, every positive test stayed green and only a negative test caught it. To write these cases in a consistent format, see our how to write test cases guide.

Frequently asked questions

What is the difference between positive and negative testing?

Positive testing uses valid input and checks that the feature works. Negative testing uses invalid or unexpected input and checks that the system rejects it safely with a clear error.

What is an example of a negative test case?

Entering an age of 121 when the allowed range is 18 to 120, and checking that the form rejects it with an age error and saves nothing.

Which should be done first, positive or negative testing?

Usually positive testing, because there is little point testing error handling if the main flow is broken. Negative testing should follow before release.

How many negative test cases do I need?

At least one per input rule, plus both sides of each boundary. Add more for high-risk areas such as payments, security and data integrity.

When does a negative test pass?

It passes when the system rejects the invalid input correctly: the right error, no crash, no saved data and no leaked details.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →