TDD vs Unit Testing vs BDD: How They Differ and When to Use Each

Talha's profile picture
Talha MalikLast Updated on
10-11 Min Read TimeAdd as preferred on Google

Key Takeaways

Unit testing is a type of test, TDD is a test-first workflow that uses those tests to shape design, and BDD agrees behavior with non-engineers.

  • A unit test checks one small piece of code. Writing tests after a feature is finished is unit testing; it becomes TDD only when each test is written first.
  • A test written first has to describe behavior, which forces design decisions early. Tests written after the code tend to describe the implementation.
  • Red-Green-Refactor means write a failing test, write the least code that passes, then clean up. Fowler says teams most often neglect the refactor step.
  • BDD sits one level above TDD. Product, QA and developers agree on Gherkin examples, and developers can still build the code behind each scenario with TDD.
  • TDD usually pays off for logic-heavy code with clear requirements. A 2009 Microsoft Research write-up reported 60 to 90 percent better defect density, with projects taking 15 to 35 percent longer.
  • In an existing codebase, require a failing test for every bug fix. Avoid a coverage target, since it pushes teams back to writing tests after the code.

Try test-first bug fixes for one quarter and measure escaped defects before committing further.

In TDD vs unit testing, one is a workflow and the other is an artifact: a unit test is code that checks one small piece of software, and test-driven development (TDD) writes that test before the production code and lets it shape the design. Writing unit tests after a feature is finished is unit testing, and it becomes TDD only when each test is written first and seen to fail. The difference shows up as a team grows, because tests written after the code tend to confirm whatever the code already does, including edge cases nobody decided on.


TDD vs unit testing vs BDD compared

Unit testing, TDD and behavior-driven development (BDD) work at different layers, so a team can use one, two or all three. The table compares them on what each one is, when the test is written, who it is for and how it tends to fail.

Unit testingTDDBDD
What it isA type of test that checks one function, class or module in isolationA development workflow of short test-first cyclesA collaboration practice that turns agreed examples into executable specifications
When the test is writtenBefore or after the code; usually after in teams that don't practice TDDBefore the production code, one failing test at a timeBefore development starts, when product, QA and engineering agree on examples
Written inThe code's own language, with a framework such as pytest, JUnit or JestThe same frameworks as unit testingGherkin (Given, When, Then) plus step definitions in code
Main readerDevelopersDevelopersProduct owners, business analysts, QA and developers
Typical scopeOne unit, with its dependencies fakedMostly units; some teams start each feature from a failing acceptance testOne user-visible behavior, tested through the API or the UI
What it leaves behindA regression suiteProduction code, its unit tests and a design refactored in small stepsFeature files that work as acceptance tests and readable documentation
Common way it goes wrongTests mirror the implementation and miss behavior nobody specifiedThe refactor step gets skippedQA writes scenarios alone after the code exists, producing slow UI scripts

The three fit inside one another. A BDD scenario describes what a user should see, TDD builds the code behind it in small test-first steps, and unit tests are what those steps leave behind. A team can write unit tests without TDD, and practice TDD without BDD.


What changes when the test is written first

Martin Fowler's definition puts it plainly: TDD "is a technique for building software that guides software development by writing tests." The word that matters is "guides". A test written after the code is written by someone who already knows how the code works, so it tends to describe the implementation. A test written first has to describe the behavior, and that forces decisions before any code exists.


Those decisions are the design work. To write the first test, a developer has to name the function, choose its inputs and decide what happens at the boundary of each rule. If the test is awkward to write because the code needs a live database or a global clock, that awkwardness is a design signal. It shows up while the code is still a few lines long and cheap to change.


The failing run also does a job. A test that has never failed may be checking nothing: a wrong import, an assertion that is always true, a mocked function that never runs. Watching it fail first proves it can catch the bug it was written for.


The Red-Green-Refactor cycle with pytest

Red-Green-Refactor is TDD's loop: write a failing test (red), write the least code that makes it pass (green), then clean up the code while every test stays green (refactor). Fowler says the most common way to get TDD wrong is neglecting the refactor step.


Take an illustrative rule from a travel booking product: a traveler who cancels 24 hours or more before departure gets a full refund, and anyone who cancels later gets half.


Step 1 (red) is to write the first test before refunds.py exists.

# test_refunds.py
from datetime import datetime, timedelta
from refunds import refund_amount

DEPARTURE = datetime(2026, 12, 1, 9, 0)

def test_full_refund_when_cancelled_exactly_24_hours_before():
    cancelled_at = DEPARTURE - timedelta(hours=24)
    assert refund_amount(200.0, DEPARTURE, cancelled_at) == 200.0

Running pytest fails because the module doesn't exist. The test name already records a decision the written rule left open: a cancellation exactly 24 hours out gets the full refund.


Step 2 (green) is to write the least code that passes.

# refunds.py
def refund_amount(fare, departure, cancelled_at):
    return fare

Returning the fare unchanged looks too simple, and that is the point. The next test has to force the real logic.

def test_half_refund_when_cancelled_less_than_24_hours_before():
    cancelled_at = DEPARTURE - timedelta(hours=23)
    assert refund_amount(200.0, DEPARTURE, cancelled_at) == 100.0

That test fails (red), and a two-line condition makes both pass (green).


Step 3 (refactor) starts once both tests are green. Name the business rules and add type hints. Running pytest after each small change confirms the behavior hasn't moved.

# refunds.py
from datetime import datetime, timedelta

FULL_REFUND_NOTICE = timedelta(hours=24)
LATE_CANCELLATION_SHARE = 0.5

def refund_amount(fare: float, departure: datetime, cancelled_at: datetime) -> float:
    notice = departure - cancelled_at
    if notice >= FULL_REFUND_NOTICE:
        return fare
    return fare * LATE_CANCELLATION_SHARE

Written after the fact, the same function could easily have shipped with > instead of >=, and a test-after suite would have asserted whatever the code returned. In production code, money belongs in Decimal; that change would be the next test-driven cycle.


Where BDD fits alongside TDD

BDD works one level above TDD: it agrees on behavior with the people who own the requirement, then automates those agreements as tests. Cucumber's documentation describes BDD as three practices, Discovery, Formulation and Automation. In discovery, the team talks through concrete examples of a change. Formulation writes those examples in Gherkin, which the same documentation calls "a medium that can be read by both humans and computers."


The discovery conversation usually involves a developer, a tester and a product owner or business analyst, often called the Three Amigos. The refund rule from the pytest example becomes a scenario that all three can read and challenge:

Feature: Cancellation refunds

  Scenario: Cancelling exactly one day before departure
    Given a booking with a fare of 200 USD departing on 1 December at 09:00
    When the traveler cancels on 30 November at 09:00
    Then the traveler is refunded 200 USD

  Scenario: Cancelling on the day of departure
    Given a booking with a fare of 200 USD departing on 1 December at 09:00
    When the traveler cancels on 1 December at 07:00
    Then the traveler is refunded 100 USD

Acceptance criteria and BDD scenarios overlap but do different jobs. Acceptance criteria are an informal checklist that marks a user story as done ("the user can cancel a booking and see the refund amount"). A BDD scenario is one concrete example with real values, structured so a tool can run it. Teams often write the criteria first, then turn the ones with business rules into scenarios.


In automation, step definitions connect each Gherkin line to code. Cucumber covers several languages, Behave is the common Python choice, and .NET teams use Reqnroll, the fork that replaced SpecFlow after SpecFlow reached end-of-life on December 31, 2024. Inside each scenario, developers can still build the underlying code with TDD. For a working setup that runs Gherkin scenarios in a browser, see our walkthrough of end-to-end testing with Playwright and Cucumber.

How QA teams get the most from BDD

For QA, the biggest payoff comes before any code exists. Writing the first scenario forces the team to state each rule with real values, so gaps in the requirement surface during discovery, when fixing them costs a sentence rather than a rework. The refund rule above is typical: the written rule said nothing about a cancellation exactly 24 hours out until someone wrote that example. The practices that keep a scenario suite useful are simple:

  • Keep one behavior per scenario, so a failure points to one rule.
  • Automate the scenarios that guard regressions and critical user journeys, and leave the rest as readable documentation.
  • Store feature files in version control next to the code, so scenario changes get reviewed like code changes.
  • Run the automated scenarios in the CI/CD pipeline, so a broken behavior shows up on the commit that broke it.


Is test-driven development worth it?

For logic-heavy code with clear requirements, TDD usually earns back its upfront cost; for exploratory or presentation work, it often doesn't. The best-known industrial evidence points both ways. A 2009 Microsoft Research write-up reported that TDD teams produced code with 60 to 90 percent better defect density than non-TDD teams, and that the same teams took 15 to 35 percent longer to complete their projects.


So the objection that TDD slows delivery is partly true at the start. The return arrives later: during a re-platform, when a refactor touches code nobody has opened in a year, or when a newly hired developer changes a pricing rule and gets told within seconds what broke. A team in a hiring surge or a cloud migration gets more from that safety net than a three-person team building a prototype it may discard.


TDD pays off most for:


  • business rules with many conditions, such as pricing, refunds, permissions or eligibility
  • data transformations and parsers with edge cases
  • libraries and shared services that many teams call
  • bug fixes, where a failing test reproduces the bug before the fix


It pays off least for throwaway spikes where nobody yet knows the requirement, visual layout work that a screenshot or a person checks better, and thin glue code over a framework. Code dominated by calls to external systems also fits poorly, because the tests end up mostly testing mocks.


How to introduce TDD to an existing codebase

Start where the cost is lowest and the feedback is fastest. A practical sequence for a team with a large untested codebase:


  1. Require a failing test with every bug fix. It is a small habit and builds the suite where defects have already appeared.
  2. Use TDD for new modules with real business logic, and leave legacy code alone until someone needs to change it.
  3. Before refactoring legacy code, write tests that record its current behavior, even where that behavior looks wrong, then change it deliberately.
  4. Keep unit tests fast enough to run on every save and run the full suite on every commit in CI. A suite that takes ten minutes stops being run locally.
  5. Review tests in code review with the same care as production code, and pair new developers with someone who already works test-first.


Avoid making a coverage percentage the goal. A team chasing 90 percent coverage writes tests after the code to hit the number, which brings back the test-after problem TDD was meant to fix. TDD is a form of shift-left testing, and it works best as part of a wider plan for keeping agile testing aligned with changing requirements.


Frequently asked questions

Can you do TDD without unit tests?

Yes, the test-first cycle works at any level, and some teams start each feature with a failing acceptance or integration test, then drive the inner code with unit tests. Running the whole cycle on slower tests stretches each loop from seconds to minutes, which is why most TDD happens at the unit level.

Which tools support TDD in Python and JavaScript?

In Python, pytest is the common choice, and the standard library's unittest works without extra installs. In JavaScript and TypeScript, Jest and Vitest both offer watch modes that rerun affected tests on save, which keeps the red-green loop short. Any framework that runs fast and reports failures clearly will support TDD.

Do QA engineers have a role in TDD?

TDD is mainly a developer practice, but QA engineers add value around it. They help define edge cases before coding, write and review BDD scenarios, and run exploratory testing that automated unit tests can't replace.

Is BDD the same as acceptance testing?

No. Acceptance testing checks whether a feature meets the criteria for release, by any method. BDD is a way of agreeing on behavior through concrete examples before development starts, and its automated scenarios often become the acceptance tests. A team can run acceptance tests without BDD, but it then skips the shared discovery conversation BDD is built around.

Do you need Cucumber to do BDD?

No. The discovery conversation and the agreed examples are the core of BDD, and neither needs a tool. Cucumber, Behave and Reqnroll automate Gherkin scenarios, but some teams express the same examples as plainly named tests in pytest or Jest. A Gherkin tool earns its place when product owners and analysts need to read and review the scenarios.


Choosing between TDD, BDD and plain unit tests

The TDD vs unit testing choice is rarely either-or. Keep writing unit tests everywhere, adopt TDD for the logic-heavy parts of the codebase where requirements are clear, and add BDD where business rules need sign-off from people outside engineering. If your team is weighing the upfront slowdown against regression pain, start with test-first bug fixes for one quarter and measure escaped defects. To plan the test automation around that practice, talk to our team about automated testing services.

...Loading Related Blogs

Explore More

From Introduction to Proposal in Days

Discovery Call
Our sales team reviews your message and asks for a discovery call to gather more information.
Expert Input
Our veterans go through your requirements to provide their take, backed by decades of experience.
Proposal
We provide a proposal specific to what you're building, for you to review at your own pace.

Trusted by top platforms for our transformative solutions and exceptional results:

How Can We Help You Build?

We recommend using your work email.
We'll send a mutual NDA before the discovery call if requested. Zero obligation.