1. Home
  2. Blog
  3. Software Testing

Software Testing

Black Box vs White Box Testing: Differences, Techniques and a Real Example

One approach tests what software does. The other tests how it does it. See a real example where three passing tests miss a bug, and learn which techniques to use and when.

9 min read
Black box vs white box testing: differences, techniques and a real example

Key takeaways

  • Black box testing checks behaviour against requirements, without looking at the code.
  • White box testing designs tests from the code’s internal logic and paths.
  • Black box finds missing or wrong features. White box finds hidden branches and untested logic.
  • Neither is enough alone, and grey box testing combines partial knowledge of both.

The debate over black box vs white box testing is really about where your test ideas come from. Do you start from what the software is supposed to do, or from how the code is actually written? Each view reveals bugs the other can miss, which is why strong teams use both.

In this guide we compare them, then test one small function from both angles. We ran that example on Python 3.13, and the output below comes from that run. The bug in it was planted deliberately, to show what each approach can and cannot see.

The short answer

Black box testing treats the software as a sealed box. You supply inputs, observe outputs and compare them with the requirements. You do not need to read the code, so tests stay valid even when the internals are rewritten. It is also known as behavioural or specification-based testing.

White box testing opens the box. You read the code and design tests to exercise its branches, loops and conditions. It requires programming knowledge, and is also called clear box, glass box or structural testing.

Black box vs white box testing side by side

Aspect Black box White box
Test basis Requirements and specifications Source code and design
Code knowledge Not needed Required
Main question Does it do the right thing? Does every path work properly?
Usually done by QA engineers, and sometimes users Developers and SDETs
Typical level System and acceptance Unit and integration
Finds Missing features, wrong behaviour, usability problems Dead code, logic errors, untested branches
Measured by Requirements covered Code coverage
Weakness Cannot see hidden paths Cannot see features that were never built

A real example: same function, two views

Here is the requirement for a shipping fee: orders of 1000 or more ship free, members pay 25 and everyone else pays 50. Here is the code, which contains a leftover rule nobody documented:

def shipping_fee(total, is_member):
    if total >= 1000:
        return 0
    if is_member:
        return 25
    if total > 900:
        return 0  # leftover promo code nobody remembered
    return 50

The black box tests

A tester who only reads the requirement would quite reasonably write one test per rule:

class BlackBox(unittest.TestCase):
    def test_free_at_1000(self):
        self.assertEqual(shipping_fee(1000, False), 0)

    def test_member_fee(self):
        self.assertEqual(shipping_fee(500, True), 25)

    def test_regular_fee(self):
        self.assertEqual(shipping_fee(500, False), 50)

The white box test

A developer reading the code sees a branch for totals above 900, which no requirement mentions. So they write a test specifically to reach it, using the fee that the requirement says should apply:

class WhiteBox(unittest.TestCase):
    def test_hidden_branch(self):
        self.assertEqual(shipping_fee(950, False), 50)

The result

test_free_at_1000 (__main__.BlackBox.test_free_at_1000) ... ok
test_member_fee (__main__.BlackBox.test_member_fee) ... ok
test_regular_fee (__main__.BlackBox.test_regular_fee) ... ok
test_hidden_branch (__main__.WhiteBox.test_hidden_branch) ... FAIL

AssertionError: 0 != 50

All three black box tests pass, yet customers spending between 901 and 999 get free shipping, and the business loses money. Reading the code exposed this immediately.

The reverse also happens. Suppose the requirement had also said “add a surcharge for remote areas”, and nobody built it. White box tests would pass, since there is no code to examine. Only a test derived from the requirement would reveal the gap. White box testing cannot find what is missing, and black box testing can struggle to find what is hidden.

Black box testing techniques

Good black box testing is not guesswork. These techniques help you choose a small set of valuable tests:

  • Equivalence partitioning: divide inputs into groups that should behave the same, then test one value from each.
  • Boundary value analysis: test at the edges, such as 999, 1000 and 1001 here, since bugs cluster around limits.
  • Decision table testing: list every combination of conditions, such as member or not with each total range.
  • State transition testing: check that an order moves correctly between states, such as pending, paid and shipped.
  • Use case testing: follow a user’s whole journey from start to finish.

In our example, boundary analysis around 1000 would test 999 and might have caught the bug by chance. That is useful, but only testing 950 or 999 reveals it, and nothing in the requirement points to 900. Exploratory testing is another strong partner here, because it follows hunches that scripted rules would not suggest.

White box testing techniques

  • Control flow testing: design tests to walk through the code’s paths.
  • Data flow testing: follow a variable from where it is set to where it is used, to spot errors such as using it before assignment.
  • Loop testing: run loops zero times, once and many times.
  • Mutation testing: a tool makes small changes to your code, such as turning >= into >, and checks that a test fails. If none does, your tests are weak.
  • Static analysis and code review: examine code without running it, which is especially valuable for security.

Statement, branch and path coverage

White box testing is usually measured with code coverage. The types differ in how strict they are:

Type What it requires Strength
Statement coverage Every line runs at least once Basic
Branch coverage Every if goes both true and false Stronger
Path coverage Every possible route through the code Strongest, but often impractical

In our function, the three black box tests left the line return 0 inside the promo branch unexecuted. A coverage report would have highlighted that gap with no need to read every line by hand, which is a practical way to find hidden logic.

Tip: Treat coverage as a way to find untested code, not as proof of quality. A test can run a line without checking its result properly, so 100 percent coverage can still miss bugs.

What is grey box testing?

Grey box testing sits between the two. The tester has partial knowledge of the internals, such as the database schema or API design, but still tests from the outside. For example, you might submit a form through the user interface and then query the database to confirm the row was written correctly. Much API testing works this way, as our guide to API testing with Postman shows, because you know the contract without reading the implementation.

Which test level uses which?

Level Usual approach Example
Unit Mostly white box Test each branch of a function
Integration Grey box Check a service writes correctly to its database
System Mostly black box Run a full checkout in a browser
Acceptance Black box Users confirm that it meets business needs

These are tendencies, not strict rules. A unit test can absolutely be written from the requirement alone. Our comparison of unit vs integration testing explains the levels in more detail.

Black box and white box in security testing

The same terms are used in security assessments. In a black box penetration test, the assessor starts with little information, much like an outside attacker. In a white box assessment, they receive source code and architecture details, which allows deeper coverage in less time. Many organizations use both, and grey box is a common compromise. Only ever test systems you own or have written permission to assess.

When to use each

Choose black box testing when you want to validate requirements, test user journeys, check a third-party component whose code you cannot read, or run acceptance tests with non-programmers.

Choose white box testing when you are writing unit tests, working on complex logic such as pricing or permissions, reviewing security-sensitive code or looking for untested branches.

In practice, ask both questions for any important feature. Start with tests from the requirements, then check a coverage report and read the uncovered code. Each uncovered branch is either a missing test, dead code that should be deleted, or an undocumented rule that needs a decision.

Common mistakes

  • Treating them as competitors. They answer different questions, so choosing one leaves blind spots.
  • Writing white box tests that copy the code. If a test repeats the implementation, it will repeat the bug too. Take expected values from the requirement.
  • Chasing a coverage number. Teams can hit a target with weak assertions. Review what the tests actually check.
  • Tying tests to internals. Tests that depend on private details break during harmless refactors.
  • Thinking black box means unplanned. It still needs test design, using the techniques above.

Final thoughts

Black box testing tells you whether you built the right thing, and white box testing tells you whether you know everything your code does. Try this on your next feature: write tests from the requirement first, run a coverage tool, and then investigate every line that was missed. As our example shows, that is often where the surprises are.

Frequently asked questions

What is the main difference between black box and white box testing?

Black box testing checks behaviour from the outside, without seeing the code. White box testing designs tests from the code’s internal structure and logic.

Is unit testing black box or white box?

Unit testing is usually considered white box, since developers know the code. A unit test can still be written purely from the requirement, though.

Who performs white box testing?

It is usually done by developers or SDETs, because it requires reading code and understanding programming, architecture and logic.

Is API testing black box or white box?

It is often black box or grey box. You test through the public contract, and you may use knowledge of the design or database to choose your checks.

Which is better, black box or white box testing?

Neither is better overall, because they find different problems. Use both for important features, and grey box testing when you have partial knowledge.

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

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 →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

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 →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →