What is unit testing in software development? It is the habit of proving, with small automated checks, that each building block of a program does exactly what it should before anyone combines the blocks into a product. Every serious codebase relies on it, from payment platforms to mobile apps, because a failing unit test points to the broken line within seconds, long before a customer finds the bug.
Unit tests are not the whole quality story. They are the developer-owned base layer of a wider software QA and testing services strategy that also covers integration, regression and end-to-end checks. When the base layer is thin, every other layer gets slower and more expensive, and release dates start to depend on luck.
This guide gives you a plain definition, the anatomy of a unit test, a worked example in Python and JavaScript, how unit tests compare with other test types, how much code coverage to expect, which frameworks teams use in 2026, what AI coding assistants change, and a checklist for judging the unit tests of any development team.
What is unit testing in software development?
Unit testing in software development is a testing level in which the smallest testable part of an application, called the unit under test, is checked in isolation by automated tests that developers write. It is the first level of testing, before integration, system and acceptance testing, and it runs on every code change.
A “unit” is usually a function, a method or a class. In some languages and teams it is a small module with a public interface. What matters is that the unit has a clear input and a clear expected output, and that it can be exercised without starting the whole application. A unit test never needs a real database, a running web server or a network call to pass.
There are two schools of thought on how big a unit should be. The classicist school, sometimes called the Detroit or Chicago school, treats a unit as a unit of behaviour: a small cluster of real objects tested together, with test doubles only at slow or external boundaries. The mockist school, often called the London school, treats each class as the unit and replaces every collaborator with a mock. Both work; many teams lean classicist and mock only at boundaries, because heavily mocked tests break whenever the internal design changes.
Unit testing is a white-box practice. The person writing the test knows how the code is built and uses that knowledge to choose inputs that reach every branch. That is why developers, not separate testers, write almost all unit tests.
Unit testing definition: what are unit tests in software development?
A unit test is a small program that calls one unit of code with known input and asserts that the output, return value or side effect matches what is expected. If the assertion holds, the test passes; if not, it fails and reports which expectation was broken. A collection of these tests, run automatically, is the unit test suite.
A good working definition of unit testing for software development has four parts: the target is the smallest testable unit, the unit is isolated from its dependencies, the check is automated and repeatable, and the result is a binary pass or fail that needs no human interpretation.
Anatomy of a unit test: Arrange, Act, Assert
Most unit tests follow the Arrange, Act, Assert pattern, usually shortened to AAA. Arrange prepares the input data and any test doubles. Act calls the unit once. Assert compares the result with the expected value. Keeping these three steps visible makes a test easy to read and easy to debug when it fails.
Behaviour-driven teams describe the same structure as Given, When, Then: given a cart worth $200, when a 25% discount is applied, then the total is $150. The wording differs, but the shape of the test is identical. One test should have one Act step and assert one behaviour, even if that behaviour needs two or three related assertions.
Test case, test suite, test runner: the vocabulary
Unit testing has a small vocabulary that shows up in every framework, every pull request review and every vendor report. The table below defines the terms you will hear most often.
| Term | Meaning | Example |
|---|---|---|
| Unit under test | The function, method or class being checked | apply_discount() |
| Test case | One scenario with specific input and an expected result | “25% off $200 returns $150” |
| Assertion | The statement that compares actual and expected values | assert total == 150 |
| Fixture | Reusable setup data or objects shared by several tests | A sample customer record |
| Test suite | A group of related test cases run together | All tests for the pricing module |
| Test runner | The tool that discovers, runs and reports tests | pytest, Jest, JUnit Platform |
| Test double | A stand-in for a real dependency during the test | A fake payment gateway |
A simple unit testing example, step by step
The clearest way to understand unit testing is to read a real test. The example below checks a small pricing function in Python with pytest, then shows the same idea in JavaScript with Jest (Vitest uses the same syntax). Both versions follow Arrange, Act, Assert.
The function under test, apply_discount(price, percent), applies a percentage discount and rejects invalid percentages. Its three tests look like this:
import pytest
from pricing import apply_discount
def test_applies_percentage_discount():
assert apply_discount(200.0, 25) == 150.0
def test_zero_percent_returns_original_price():
assert apply_discount(99.99, 0) == 99.99
def test_rejects_percent_above_100():
with pytest.raises(ValueError):
apply_discount(50.0, 120)
Each test checks one behaviour: a normal discount, the zero edge case and an invalid input that must raise an error. pytest finds every function whose name starts with test_, runs it and reports which assertions failed. The whole file runs in a few milliseconds because nothing touches a disk, a database or a network.
// discount.test.js
const { applyDiscount } = require('./discount');
test('applies a percentage discount', () => {
const price = 200; // Arrange
const result = applyDiscount(price, 25); // Act
expect(result).toBe(150); // Assert
});
test('rejects a negative percent', () => {
expect(() => applyDiscount(50, -5)).toThrow(RangeError);
});
The JavaScript version labels the three AAA steps explicitly. In real projects these comments are usually omitted once a team is used to the pattern, but the order stays the same. Notice that the test names read like requirements. When rejects a negative percent fails in a pull request, a reviewer knows what broke without opening the code.
Why is unit testing important?
Unit testing is important because it catches defects at the moment and place where they are cheapest to fix, gives developers a safety net for refactoring, and documents how each piece of code is supposed to behave. Without it, bugs travel further down the pipeline and cost more at every stage.
The economic argument is well documented. NIST’s Planning Report 02-3, published in 2002, estimated that inadequate software testing infrastructure cost the US economy about $59.5 billion a year, and that about $22.2 billion of that could feasibly be avoided through better testing. More recently, the Consortium for Information & Software Quality (CISQ) estimated in its 2022 report that the cost of poor software quality in the US had reached at least $2.41 trillion. The figures differ in scope and method, but both point to the same conclusion: defects that escape early checks become expensive.
Unit tests also change how teams work day to day:
- Fast feedback. A developer learns within seconds that a change broke something, while the code is still fresh in mind.
- Safe refactoring. Engineers can restructure or upgrade code because the suite proves behaviour did not change.
- Living documentation. Test names and assertions describe business rules more reliably than a wiki page.
- Better design. Code that is easy to test tends to have small functions and explicit dependencies.
- Cheaper debugging. A failed unit test points to one function, not to a whole user journey.
This is the core of the shift-left approach: move checks to the earliest possible moment, and the unit test is the earliest automated check there is.
How does unit testing work in the development workflow?
In a modern workflow, unit tests are written alongside the code, run on the developer’s machine, and then run again automatically in continuous integration on every pull request. A change is merged only when the whole suite is green. The typical sequence looks like this:
- Pick the unit. Identify the function or class you are adding or changing.
- Define expected behaviour. List the normal case, the edge cases (empty, zero, maximum) and the error cases.
- Isolate dependencies. Replace databases, clocks, network clients and random generators with test doubles or injected values.
- Write the tests in AAA form. One behaviour per test, with a name that reads like a requirement.
- Run locally. Use watch mode or a pre-commit hook so tests run before code leaves the laptop.
- Run in CI on every pull request. The pipeline blocks the merge if any unit test fails or coverage on changed lines drops.
- Keep tests in sync. When behaviour changes on purpose, update the test in the same commit; when a bug is found, add a test that reproduces it first.
Steps 6 and 7 are where many teams slip. A suite that runs only on developer machines decays quickly. Our guide to CI/CD in software development shows how the unit stage fits into the pipeline, and the article on pull requests explains how reviewers use test results as a merge gate.
Unit testing vs integration testing vs end-to-end testing
Unit testing checks one piece of code in isolation, integration testing checks that pieces work together, and end-to-end testing checks complete user journeys through the real system. Each level catches a different kind of defect, so a healthy project uses all of them in different proportions.
| Type | What it checks | Scope | Speed | Who writes | Typical tools | Catches |
|---|---|---|---|---|---|---|
| Unit | One function, method or class | Smallest | Milliseconds | Developers | pytest, JUnit, Jest | Logic and edge-case errors |
| Integration | Several units or a unit plus a real dependency | Small to medium | Seconds | Developers, QA | Testcontainers, Spring Test, Supertest | Wiring, queries, configuration |
| Functional / API | A feature through its public interface | Medium | Seconds | QA, developers | Postman, REST Assured, Pact | Contract and business-rule errors |
| End-to-end / UI | A full user journey in a deployed app | Whole system | Minutes | QA automation | Playwright, Cypress, Appium | Broken flows across services |
| Regression | That old features still work after a change | Any level | Varies | Whole team | The existing suites, re-run | Side effects of new code |
| UAT | That the product meets business needs | Whole system | Days | Business users | Test scripts, staging | Wrong requirements |
Regression is not a separate level so much as a purpose: re-running existing tests after every change. User acceptance testing sits at the opposite end from unit tests, with business users checking the product against real needs. For the full landscape of test types, see our guide to quality assurance in software development.
Where unit tests sit in the testing pyramid
Unit tests form the wide base of the testing pyramid: many fast, cheap tests at the bottom, fewer integration tests in the middle and a small number of slow end-to-end tests at the top. The shape keeps feedback fast and the suite stable.
A 2015 Google Testing Blog post by Mike Wacker, “Just Say No to More End-to-End Tests”, popularised a rule of thumb of roughly 70% unit, 20% integration and 10% end-to-end tests. The post itself says the exact mix will be different for each team, but that the suite should keep its pyramid shape. Treat the ratio as a starting point, not a mandate.
Frontend teams sometimes prefer the “testing trophy” described by Kent C. Dodds, which puts more weight on integration tests of components and less on isolated unit tests. The trophy and the pyramid agree on the main point: slow, brittle end-to-end tests should be the smallest group.
Unit testing in the V-model
In the V-model, unit testing is the verification step paired with detailed or module design. The left side of the V moves from requirements down to module design and coding; the right side climbs back up from unit testing through integration, system and acceptance testing, and each test level checks the design level opposite it. Regulated industries still use this model, and our article on the V-model in software development explains how its test levels map to documentation.
Mocks, stubs and fakes: how to isolate the unit
Test doubles are stand-ins that replace slow, unpredictable or external dependencies, such as databases, payment gateways, clocks and HTTP clients, so a unit can be tested on its own. They keep unit tests fast and deterministic, and they let you simulate errors that are hard to trigger with the real dependency.
| Double | What it does | Use when | Example |
|---|---|---|---|
| Dummy | Fills a parameter but is never used | A signature needs an argument the test does not care about | An empty logger object |
| Stub | Returns fixed, canned answers | You need the dependency to return a specific value | An exchange-rate client that always returns 1.10 |
| Fake | A working but simplified implementation | You need realistic behaviour without the real system | An in-memory repository instead of PostgreSQL |
| Spy | Records how it was called | You need to check that a call happened, after the fact | An email sender that stores sent messages |
| Mock | Pre-programmed with expectations and verifies them | The interaction itself is the behaviour under test | A payment gateway that must be charged exactly once |
Test doubles work best with dependency injection: instead of creating a database client inside a function, the code receives it as a parameter or constructor argument. The production code passes the real client, and the test passes a fake. Code that creates its own dependencies, reads the system clock directly or calls static global services is hard to test and is usually the first thing a team refactors when it starts unit testing seriously.
Over-mocking is the opposite problem. When every collaborator is mocked and each test verifies exact call sequences, the tests mirror the implementation instead of the behaviour. Any refactor then breaks dozens of tests even though the product still works. A practical rule: mock what you do not own or cannot control (networks, third-party APIs, time), and use real objects or fakes for your own simple classes.
Unit testing techniques: white-box, black-box and gray-box
Unit tests are mostly designed with white-box techniques, because the developer can see the code, but black-box and gray-box thinking help choose better inputs. Combining them produces tests that cover both the internal branches and the external contract of a unit.
- White-box testing. Inputs are chosen to exercise every branch, loop and condition in the code, guided by coverage reports.
- Black-box testing. The unit is tested only through its public interface against its specification, without relying on internal details.
- Gray-box testing. The tester knows some internals, such as the data model, and uses that knowledge to design interface-level tests.
- Equivalence partitioning. Inputs are grouped into classes that should behave the same, and one value from each class is tested.
- Boundary value analysis. Tests target the edges of each range, such as 0, 100 and 101 for a percentage, where off-by-one errors live.
- Parameterized tests. One test body runs against a table of inputs and expected outputs, which keeps edge cases compact.
- Property-based testing. Tools such as Hypothesis for Python and fast-check for JavaScript generate hundreds of random inputs and check that a property, like “a discount never increases the price”, always holds.
Manual vs automated unit testing
In 2026, unit testing is almost entirely automated. Manually stepping through a function in a debugger or printing values to a console can confirm a single case, but it leaves no reusable check behind and does not scale past a handful of functions.
- Repeatability. An automated test runs identically thousands of times; a manual check depends on who performs it and how carefully.
- Speed. A suite of several thousand unit tests typically finishes in seconds to a few minutes in CI.
- Regression protection. Automated tests keep guarding old behaviour long after the original developer has moved on.
- Evidence. CI logs and coverage reports give managers and auditors proof that checks actually ran.
- Where manual still helps. Exploratory debugging is useful for understanding a failure, but the finding should end as a new automated test.
What makes a good unit test? The FIRST principles
A good unit test is fast, independent, repeatable, self-validating and timely, the five qualities captured by the FIRST acronym popularised by Tim Ottinger and Jeff Langr. Tests that break these principles become slow, flaky or ignored.
| Principle | Meaning | Smell when broken |
|---|---|---|
| Fast | Runs in milliseconds, so the full suite runs on every change | Developers skip tests locally because “they take too long” |
| Independent | Does not depend on other tests or their order | Tests pass alone but fail when run together |
| Repeatable | Gives the same result on any machine, at any time | Failures on Mondays, at midnight or only in CI |
| Self-validating | Reports pass or fail with no human interpretation | Someone has to read log output to decide |
| Timely | Written together with the code, not months later | Large untested modules nobody dares to touch |
A few more habits separate useful tests from noise. Test one behaviour per test, and give it a descriptive name such as should_reject_negative_percent, so a failure explains itself. Keep logic out of tests: loops and conditionals in a test can hide bugs of their own. Control every source of non-determinism, including the clock, random numbers, time zones and network calls. Finally, treat flaky tests, the ones that pass and fail without code changes, as defects: quarantine them, fix the cause and track the flaky rate, because a suite people do not trust stops being run.
These habits overlap with broader software development best practices such as small commits, code review and clear naming.
How much code coverage do you need?
Code coverage measures which lines or branches ran during tests, not whether their results were checked, so there is no universal target that guarantees quality. A useful benchmark comes from Google’s testing blog guideline (“Code Coverage Best Practices”, 2020), which describes 60% as acceptable, 75% as commendable and 90% as exemplary.
The same guideline stresses that coverage of the code changed in each commit matters more than a project-wide percentage. A legacy system at 45% overall can still be improving if every new pull request arrives with 85% coverage on its changed lines. Business-critical logic, such as pricing, billing, permissions and calculations, deserves close to full branch coverage, while simple glue code needs much less.
| Coverage type | Measures | Notes |
|---|---|---|
| Line / statement | Share of lines or statements executed | Easiest to collect; can look high while missing whole branches |
| Branch | Share of if/else and switch outcomes taken | Better signal for logic-heavy code |
| Condition | Whether each boolean sub-condition was true and false | Catches complex conditions that branch coverage misses |
| MC/DC | That each condition independently affects the decision | Required for the most critical avionics software |
| Mutation score | Share of injected bugs that tests detect | Shows whether assertions are real, not just whether code ran |
Mutation testing is the honest check on coverage. Tools such as PIT for Java, Stryker for JavaScript, TypeScript and C#, and mutmut for Python make small changes to the code, like flipping > to >=, and rerun the tests. If the tests still pass, the “mutant” survived and the assertions are too weak. A suite with 90% line coverage and a low mutation score is mostly executing code, not testing it.
Popular unit testing frameworks by language (2026)
Every mainstream language has a mature unit testing framework, usually paired with a mocking library, and the choice is mostly decided by the language and the team’s existing stack. The table lists the common defaults in 2026.
| Language | Framework | Mocking library | Notes |
|---|---|---|---|
| Java / Kotlin | JUnit 5 | Mockito, MockK (Kotlin) | De facto standard on the JVM; AssertJ for readable assertions |
| Python | pytest, unittest | unittest.mock, pytest-mock | pytest dominates new projects; unittest ships with Python |
| JavaScript / TypeScript | Jest, Vitest | Built-in mocks | Vitest is popular with Vite-based frontends; same API style as Jest |
| C# / .NET | xUnit.net, NUnit, MSTest | Moq, NSubstitute | xUnit.net is the common default for new .NET code |
| Go | Built-in testing | testify, gomock | Table-driven tests are idiomatic Go |
| Swift | XCTest, Swift Testing | Protocol-based fakes | Swift Testing is Apple’s newer macro-based framework |
| C / C++ | GoogleTest, Catch2 | GoogleMock | Common in embedded and performance-critical code |
| PHP | PHPUnit, Pest | Mockery, built-in mocks | Pest adds a lighter syntax on top of PHPUnit |
| Ruby | RSpec, Minitest | rspec-mocks | Minitest ships with Ruby and Rails |
The framework rarely decides whether unit testing succeeds. Team habits do: whether tests run on every pull request, whether failures block merges, and whether people trust the results.
Benefits and limitations of unit testing
Unit testing delivers fast, cheap feedback and safer change, but it cannot prove that a whole system works, and a poorly designed suite can create false confidence. Knowing both sides helps teams invest in the right amount of unit testing.
| Benefits | Limitations |
|---|---|
| Finds defects the moment they are introduced | Does not catch integration, configuration or UI problems |
| Makes refactoring and upgrades safe | Needs ongoing maintenance as the code changes |
| Documents behaviour in executable form | Shallow assertions give false confidence |
| Speeds up debugging by pinpointing the failing unit | Over-mocked tests break on harmless refactors |
| Pushes code toward modular, loosely coupled design | Legacy code without seams is hard to test at first |
| Gives the cheapest feedback in the CI pipeline | Cannot verify that requirements themselves are right |
What should you not unit test?
You should not spend unit tests on code that has no logic of its own or that is better verified at another level. Unit testing everything equally wastes time and produces brittle tests that slow the team down.
- Trivial getters and setters that only store and return a value.
- Framework and library code you did not write; the framework authors already test it.
- Generated code such as ORM models or API clients produced by a generator.
- Pure configuration files and constants, which are better checked by schema validation.
- Database queries and HTTP contracts, which need a real database or contract tests at the integration level to be meaningful.
- Thin UI layout details that change often and are better covered by visual or end-to-end checks.
Legacy code is a special case. Before changing old code that has no tests, write characterization tests: tests that record what the code currently does, right or wrong. They create a safety net, after which you can refactor toward testable units and replace characterization tests with proper behavioural ones.
Unit testing vs TDD: is unit testing the same as test-driven development?
No. Unit testing is a type of test, while test-driven development is a workflow that writes the unit test before the production code and lets the test drive the design. Most teams write unit tests after or alongside the code without practising strict TDD, and still get a reliable suite. TDD is one disciplined way to make sure tests are timely and that every test has been seen to fail. Our guide to TDD in software development covers that workflow, its costs and when it pays off.
How are AI coding assistants changing unit testing in 2026?
AI coding assistants can generate unit tests in seconds, which makes it cheap to raise coverage, but generated tests often assert what the code currently does instead of what it should do. In 2026, the job shifts from typing tests to reviewing them, with mutation testing as an objective check.
Adoption is already broad. In the Stack Overflow Developer Survey 2025, 84% of respondents said they use or plan to use AI tools in their development process, up from 76% in 2024. Trust is falling at the same time: 46% said they do not trust the accuracy of AI output, compared with 31% a year earlier, and 66% named “AI solutions that are almost right, but not quite” as their biggest frustration. Respondents also listed testing among the areas where they most plan to use AI.
“Almost right” is exactly the risk with generated tests. If the code has a bug, a test generated from that code will happily lock the bug in. Teams that use AI for unit testing productively follow a few rules:
- Review every generated assertion against the requirement, not against the current output.
- Prefer behaviour over implementation. Reject tests that verify internal call sequences without a business reason.
- Run mutation tests on AI-written suites to prove the tests fail when the code is broken.
- Never let an agent fix a red test by editing the assertion. A failing test means the code or the requirement needs a human decision.
- Keep generated tests in the pull request diff, so reviewers see and approve them like any other code.
Products that include AI features need a different layer of checks on top of unit tests, because model output is not deterministic. That is the scope of AI product testing, which evaluates answers, safety and regressions in AI behaviour.
Unit testing in regulated software
In regulated industries, unit testing is not only good practice but documented evidence that auditors and certification bodies expect to see. The rules differ by domain, but they all ask for proof that units were verified and that the verification was planned.
- Medical devices. IEC 62304 requires software unit verification for software in safety Classes B and C, with acceptance criteria defined in advance.
- Avionics. DO-178C requires modified condition/decision coverage (MC/DC) for the most critical Level A software, in addition to statement and decision coverage.
- Payments and SaaS. PCI DSS and SOC 2 auditors look for evidence of automated testing and controlled change management in the delivery pipeline.
In these settings, test results, coverage reports and traceability from requirements to tests become part of the release record. Our article on medical device software development explains how this documentation fits into a regulated release process.
How to check a development team’s unit tests: a buyer’s checklist
You can judge a development team’s unit testing without reading the code by asking a few direct questions. Clear, specific answers are a good sign; vague answers about “high coverage” are not.
- Do unit tests run automatically on every pull request, and does a failure block the merge?
- What is the coverage on changed code in recent pull requests, not only the project-wide number?
- Is there a flaky-test policy, with a tracked flaky rate and a deadline for fixing quarantined tests?
- Do you measure a mutation score on critical modules, and what is it?
- What is your policy on test doubles, and what do you mock versus test with real or fake objects?
- How long does the unit suite take to run? The target is minutes, not hours.
- Who reviews AI-generated tests, and how do you check they assert the right behaviour?
If the answers are weak, or you have inherited a codebase nobody can vouch for, an independent QA audit can measure coverage, mutation score and flaky rate, and turn the findings into a concrete plan for the test pyramid.
Frequently asked questions
What is unit testing in software development?
Unit testing in software development is the practice of checking the smallest testable pieces of code, such as a function, method or class, in isolation from databases, networks and other modules. Developers write automated unit tests that call the unit with known input and assert the expected result. The tests run in milliseconds on every change and form the first, fastest level of software testing.
What are unit tests in software development, with an example?
Unit tests are small automated programs that verify one behaviour of one unit of code. For example, a test for a function apply_discount(price, percent) can call apply_discount(200, 25) and assert that the result is 150, and a second test can assert that a percent of 120 raises an error. Each test follows Arrange, Act, Assert and runs without a database or network.
Who writes unit tests: developers or QA engineers?
Developers write unit tests, usually in the same pull request as the code they test, because unit tests need knowledge of the internal structure of the code. QA engineers rarely write them, but they shape the overall test strategy, review coverage on risky areas, build integration and end-to-end suites, and coach developers on test design and edge cases.
What is the difference between unit testing and integration testing?
Unit testing checks one unit of code in isolation, with dependencies replaced by test doubles, so tests are fast and point to the exact faulty line. Integration testing checks that several units or real components, such as a service and its database or an external API, work together correctly. Unit tests catch logic errors, while integration tests catch wiring, configuration and contract errors.
How much unit test coverage is enough?
There is no universal number, because coverage shows which code ran, not whether it was verified. Google's testing blog guideline treats 60 percent as acceptable, 75 percent as commendable and 90 percent as exemplary, and stresses coverage of changed code in each commit over a project-wide figure. Critical business logic deserves close to full branch coverage, while trivial code needs little.
Is unit testing the same as TDD?
No. Unit testing is a type of test, while test-driven development (TDD) is a workflow that decides when the test is written. In TDD, a developer writes a failing unit test first and then writes the code that makes it pass. Most teams write unit tests without practising strict TDD, and both approaches can produce a reliable unit test suite.
Can AI write unit tests for my codebase?
Yes, AI coding assistants can generate unit tests quickly, and testing is one of the areas where developers most plan to use AI. The risk is that generated tests often assert what the code currently does rather than what it should do. A developer must review every assertion, and mutation testing should confirm that the tests actually fail when the code is broken.
Sources
- NIST, Planning Report 02-3: The Economic Impacts of Inadequate Infrastructure for Software Testing (2002)
- CISQ, Cost of Poor Software Quality in the US: A 2022 Report
- Google Testing Blog, Just Say No to More End-to-End Tests (Mike Wacker, 22 April 2015)
- Google Testing Blog, Code Coverage Best Practices (7 August 2020)
- Stack Overflow, 2025 Developer Survey: AI; press release