What Is Unit Testing?
If you have done manual testing, you know the routine. You open the app, fill in a form, click a button, and check what happens. That tells you whether a feature works. What it doesn't tell you is which part of the code broke when the feature doesn't work. And you can't use it to recheck everything each time a developer changes a line.
Unit testing fills that gap. Instead of testing the whole app from the outside, it tests the small pieces of code inside it, one at a time, automatically, in milliseconds.
This guide explains unit testing from the ground up. It starts with what a "unit" actually is, then compares unit testing with the manual testing you may already know, shows why one can't replace the other, looks at how unit testing became part of everyday development, and ends with how unit tests actually work in practice.
- What a unit is
- Unit testing vs manual testing
- A simple unit test example
- Why you need both
- Why unit testing is worth it
- How unit testing became mainstream
- Whether unit testing is still relevant
- Where unit testing fits among other testing terms
- How tests check behaviour with inputs and expected answers
- Stubs and mocks explained
- Where unit tests live and how they run
What Is a Unit in Unit Testing?โ
A unit is the smallest piece of code that does one job and can be tested on its own. Most of the time it's a single function or method. Sometimes it's a small class.
Take a registration form. To a user, it's one feature: fill in the fields, click Register. But behind that button, the code is broken down into small pieces:
| Unit (function) | Its one job |
|---|---|
isValidEmail(email) | Check the email looks like name@domain.com |
isStrongPassword(password) | Check it has 8+ characters, a number, and a capital letter |
calculateAge(birthDate) | Work out the user's age from their date of birth |
isOldEnough(age) | Check the user is 18 or older |
saveUser(user) | Store the new user in the database |
Each row is a unit. Unit testing means testing each of these on its own, separately from the others.
Unit Testing vs Manual Testingโ
When you test manually, you test from the outside. You open the app, type into the form, click the button and look at what happens. The whole app has to be up and running, and you can't see the code.
A unit test works from the inside. A developer writes a small piece of code that calls one function directly, gives it an input, and checks the output. No browser, no button, no database.
| Manual testing | Unit testing | |
|---|---|---|
| What it tests | A whole feature, as a user sees it | One function or method |
| How | A person clicks through the app | Code calls the function and checks the result |
| Needs the full app running? | Yes | No |
| Speed | Minutes to hours | Milliseconds |
| When it runs | When someone sits down to test | Automatically, on every code change |
| When it fails, you learn | That something broke | Which function broke, and with what input |
Think of building a car. Manual testing is driving the finished car around the block. Unit testing is checking each part on a workbench, like the brake pad or the spark plug, before it goes into the car.
The test drive tells you something feels wrong. The bench test tells you which part is faulty.
A Simple Unit Test Exampleโ
Here's the password rule from the registration form, along with three unit tests written in JavaScript with Jest:
// The unit
function isStrongPassword(password) {
return password.length >= 8 && /\d/.test(password) && /[A-Z]/.test(password);
}
// The unit tests
test('accepts a strong password', () => {
expect(isStrongPassword('Secure123')).toBe(true);
});
test('rejects a password with no number', () => {
expect(isStrongPassword('Secureabc')).toBe(false);
});
test('rejects a password shorter than 8 characters', () => {
expect(isStrongPassword('Ab1')).toBe(false);
});
Every unit test follows the same simple pattern: give the function an input, then check the output is what you expect. These three checks run in a few milliseconds, and they run automatically every time someone changes the code.
Why Manual Testing Can't Replace Unit Testsโ
Manual testing is valuable, but there are four things it can't reach.
The password rule alone has lots of cases: too short, no number, no capital, exactly 8 characters, an empty field, spaces, emojis. By hand you'd try three or four. A unit test file can try twenty in under a second.
You click Register and get "Something went wrong." Was it the email check? The age calculation? The database? A failing unit test points straight at the broken function: calculateAge failed for someone born on 29 February.
The frontend often blocks bad input, like an age of -5, before it reaches the backend. So the backend's own check never gets exercised in a manual test. But a mobile app or another service can still send it bad data. A unit test calls the function directly, so it can test those paths.
A developer changes calculateAge. Did that break anything else? Re-testing the whole app manually takes hours. Hundreds of unit tests rerun in seconds on every commit, so bugs get caught minutes after they're written.
Unit Tests Don't Replace Manual Testing Eitherโ
It works the other way too. A unit test won't notice that the Register button is hidden off-screen on a phone, or that the form is confusing to fill in.
Unit tests check that the pieces are correct. Manual testing checks that the experience works for a real person.
A healthy test strategy uses both.
Why Test Small Pieces of Code?โ
If the app works when you click through it, why bother? Because software never stands still. Developers change code every day, and any change can break something that worked yesterday, often somewhere nobody re-checks by hand.
Manual testing tells you the app works right now. Unit tests keep checking that it still works after every change.
Testing small pieces pays off in a few ways:
- Bugs are cheaper to fix early. A bug caught seconds after it's written takes a minute to fix. The same bug found by a customer means support tickets and an urgent hotfix.
- Small pieces can be checked completely.
isStrongPasswordhas maybe 15 interesting inputs, and you can test them all. The full registration flow has thousands of combinations, and nobody can. - Developers can change code without fear. They make a change, run the tests, and know within seconds if something broke.
- Tests show how the code should work. A test named
rejects a password with no numberexplains the rule better than a comment, and it can't go out of date.
Is Unit Testing Worth It?โ
Yes, when the tests are written well. One often-quoted study (Nagappan et al., 2008) followed teams at Microsoft and IBM that wrote unit tests first. They shipped 40โ90% fewer defects, for about 15โ35% more development time.
Unit tests have limits too.
- They only check what someone thought to test.
- Every piece can pass and the app can still fail when the pieces are put together.
- A badly written test still shows a green tick and gives false confidence.
- High code coverage means the lines ran, not that they were checked properly.
Unit tests don't prove the app works. They make it much harder for the pieces to quietly break.
How Unit Testing Became Mainstreamโ
Unit testing wasn't invented on a single day. It grew step by step as the way people built software changed.
| When | What changed |
|---|---|
| 1950sโ60s | Programs were often one big block of code, tested by running the whole thing. Bugs were slow to track down. |
| 1970s | Modular programming broke code down into separate modules. Testing each module on its own, called "module testing", became normal. |
| 1987 | The IEEE published IEEE 1008, a standard for software unit testing. But most unit testing was still manual and one-off. |
| 1989โ1997 | Kent Beck built SUnit for Smalltalk, then wrote JUnit for Java with Erich Gamma. Tests became code you keep and rerun automatically. |
| Late 1990sโ2000s | JUnit was copied into almost every language (the xUnit family). Extreme Programming, TDD and Agile made writing unit tests part of everyday development. |
| Today | Unit tests run automatically in CI on every code change, with tools like Jest, pytest and JUnit. |
Modular programming made unit testing possible, and automated frameworks like JUnit made it mainstream.
Is Unit Testing Still Relevant?โ
Yes. You may not hear much about it, but that's because it has become standard practice. Few people write blog posts about something everyone already does. Unit tests quietly run in nearly every serious codebase on every commit.
What has changed is the debate about how many you need:
- The Testing Trophy (popular in frontend) and the Testing Honeycomb (from Spotify, for microservices) both put more weight on integration tests, because many bugs come from pieces working together. Neither says to drop unit tests. They say not to rely on them alone.
- Integration tests got cheaper. Tools like Testcontainers make it easy to spin up a real database in a test, so some checks have moved up a level.
- AI made unit tests more important. AI coding assistants write unit tests quickly, and when AI writes or changes code, running the unit tests is one of the main ways to check its work.
For code with real logic, like calculations, rules and validation, nothing has replaced unit tests. They're still the fastest and cheapest way to check it.
- Component tests: unit tests for UI pieces, like a button or a form
- Small tests: Google's name for fast tests with no network or database
- Developer tests or microtests: tests developers write alongside their code
- Specs: from BDD-style tools like RSpec and Jasmine
- Often just "the tests", because teams take them for granted
Where Unit Testing Fits in the Testing Landscapeโ
Testing comes with a lot of terms: integration, end-to-end, performance, white-box, TDD, BDD. They can sound like different names for the same thing. They're not. Each one answers a different question:
| Question | Terms that answer it | Where unit testing fits |
|---|---|---|
| How much of the system is tested? | Unit, integration, end-to-end | Unit is the smallest level |
| What quality is checked? | Functional, performance, security | Usually functional |
| How much do you know about the inside? | White-box, black-box, grey-box | Usually white-box |
| When and how are tests written? | TDD, BDD, XP, Agile | Unit tests are at the core of most of them |
Unit vs Integration vs End-to-End Testingโ
These are the three main levels of testing, often drawn as the test pyramid:
They complement each other rather than compete:
- Unit tests check the pieces. For example,
isOldEnough(age)gives the right answer. - Integration tests check the joints. For example, the registration code really saves the user to the real database. Every unit can pass while the connection between them is broken.
- End-to-end tests drive the real app like a user would: open the browser, fill in the form, click Register. They're the automated version of manual testing.
Unit tests also keep end-to-end tests few. If every password and email rule is already checked by fast unit tests, the end-to-end test only needs to check that the main journey works. Without them, teams try to cover every edge case through the UI and end up with slow, flaky suites.
Push each check down to the lowest level that can catch it.
Unit Testing and Performance Testingโ
These check different qualities. Unit testing asks "is this piece correct?" Performance testing asks "is it fast enough, and does it hold up under load?"
Most performance testing happens at system level, for example simulating 10,000 users on the registration page. There is a small unit-level version called micro-benchmarking, which times a single function such as hashPassword. It's used for performance-critical code.
Is Unit Testing White-Box or Black-Box?โ
Usually white-box: the developer can see the code and makes sure each branch gets tested. But a good unit test still checks inputs and outputs only, like a tiny black-box test. It shouldn't care how the function works inside, so the code can be rewritten without breaking the tests.
Unit Testing in TDD, BDD and Agileโ
These aren't types of tests. They're ways of working, and each one uses unit tests in its own way:
| Methodology | What unit testing means in it |
|---|---|
| Extreme Programming (XP) | Where modern unit testing took root. All code has unit tests, and they must pass before code is merged. |
| TDD (Test-Driven Development) | Unit tests are written before the code: write a failing test, make it pass, then clean up ("red, green, refactor"). |
| BDD (Behaviour-Driven Development) | Grew out of TDD. Tests describe behaviour in plain language, like "given a user aged 17, when they register, then they're rejected". This works at unit level or full-system level. |
| Agile | Doesn't require unit tests, but short sprints and frequent releases are hard to keep up without them. |
| CI/CD | Unit tests are the first gate. They run on every commit and stop the build before anything slower runs. |
One Test, Many Labelsโ
Here's why the terms feel like they overlap: one test can wear several labels at once. Take the test rejects a password with no number. It's a unit test, a functional test, an automated test, a white-box test, part of the regression suite, and it may have been written TDD-style. All of these are true at the same time.
Testing terms aren't a list of different tests. They're different ways to describe a test.
How Unit Tests Check Behaviour: Inputs and Expected Answersโ
The expected answer is decided before the code runsโ
This is the part that surprises people. In a unit test, you write down the correct answer yourself, in advance. The test then runs the code and compares.
expect(calculateDiscount(100, 10)).toBe(90);
// โ input โ the answer you worked out
Where does 90 come from? From the rule, not from the code. The rule says "10% off", and 10% off 100 is 90. You work that out yourself, the same way a manual tester knows the expected result before clicking the button.
This matters. If you ran the code first and copied whatever it gave you into the test, you'd only be checking that the code does what the code does. A bug would get locked in as the "correct" answer. The expected value has to come from an independent source of truth: the requirement, a calculation by hand, or a known real example.
A test is a claim: "for this input, the right answer is X." The code has to prove it agrees.
Covering the full behaviour with many inputsโ
One input checks one case. To cover the whole behaviour, you pick a set of inputs that together cover every rule and every edge, each with its own expected answer.
Most frameworks let you write this as a table, which makes the idea very clear:
test.each([
// password expected why this case
['Secure123', true], // valid: meets every rule
['Secure12', true], // exactly 8 chars: boundary, just enough
['Secur12', false], // 7 chars: boundary, just too short
['secure123', false], // no capital letter
['SecureABC', false], // no number
['', false], // empty
])('isStrongPassword(%s) returns %s', (password, expected) => {
expect(isStrongPassword(password)).toBe(expected);
});
Each row is one test case: input โ expected answer. The framework runs the code six times and checks all six. This is called a parameterized or table-driven test.
The rows aren't random. They're chosen so that each rule gets one case that satisfies it and one that breaks it:
| Rule | Case that satisfies it | Case that breaks it |
|---|---|---|
| At least 8 characters | Secure12 (exactly 8) | Secur12 (7) |
| Has a capital letter | Secure123 | secure123 |
| Has a number | Secure123 | SecureABC |
| Something entered | Secure123 | empty string |
If any rule is coded wrong, at least one row fails. That's what covering the full behaviour means.
Where the test inputs come fromโ
Mostly, the person writing the test picks them by hand and types them straight into the test. Real test files are full of hard-coded values like 'a@b.com' and age: 17. Those values are chosen deliberately:
| Source | Example |
|---|---|
| The rules | "Must be 18+" โ test 17, 18 and 19 |
| Boundaries | Values right at the edge of each rule, where off-by-one bugs live |
| Categories | One valid email, one with no @, one empty, rather than 50 valid emails that all test the same thing |
| Past bugs | A user born on 29 February once broke production, so that date becomes a permanent test input |
| Real business examples | "A customer with a 10% coupon and free shipping should pay X" |
These are the same techniques manual testers use to design test cases: boundary value analysis, equivalence partitioning, and regression cases from past bugs. Unit testing applies them to single functions, written as code instead of clicks.
For complicated inputs, like a full user object with twenty fields, teams write small helper functions that fill in sensible defaults, so each test only spells out the field it cares about, such as buildUser({ age: 17 }).
There's also a more advanced technique where the framework generates hundreds of random inputs for you, called property-based testing. With random inputs you can't hand-write every answer, so you assert rules that must always hold instead. For example: "a discounted price is never negative and never more than the original."
Stubs and Mocks: Testing the Inputs and Outputs You Can't Seeโ
A simple function like isStrongPassword gets its input as an argument and gives its answer as a return value. You pass the input in and check what comes out.
Most real code isn't that tidy. Here's a more realistic registration function:
async function registerUser(input, { userRepo, emailService }) {
if (!isValidEmail(input.email)) throw new Error('Invalid email');
if (input.age < 18) throw new Error('User must be 18 or older');
if (await userRepo.findByEmail(input.email)) throw new Error('Email already registered');
await userRepo.save(input);
await emailService.sendWelcome(input.email);
return input;
}
Some of its inputs and outputs don't go through the arguments or the return value. They travel through other parts of the system, the database and the email service:
| Inputs | Outputs | |
|---|---|---|
| Direct | The arguments you pass in, such as the email and age | What it returns, or the error it throws |
| Hidden | Answers it gets from dependencies: "does this email already exist?" | Things it tells other parts to do: "save this user", "send the welcome email" |
| How a test handles it | Hidden inputs are controlled with stubs | Hidden outputs are checked with mocks |
Why not use the real database?โ
A unit test must be fast and self-contained. With the real database and email service, the test would be slow, could fail for the wrong reasons (the database is down, the network is slow), and would have real effects, like sending actual emails every time the tests run. So unit tests use stand-ins instead.
Car makers don't put a real person in a car to test the seatbelt. They use a crash-test dummy. It behaves enough like a person for the test, and it records what happened to it. Stubs and mocks are the crash-test dummies of unit testing.
Stubs control the hidden inputsโ
Partway through, registerUser asks the database whether the email already exists. That answer is an input to the logic. It just arrives from the database instead of the arguments.
To test the duplicate-email rule, you need that answer to be "yes". A stub is a fake database where you decide the answer in advance:
userRepo.findByEmail.mockResolvedValue({ id: 1 }); // stub: "yes, this email exists"
A stub is just a way to feed test data in through a dependency. It's the same idea as passing age: 17, only through a different door.
Mocks check the hidden outputsโ
When registration succeeds, the important result isn't only the return value. It's that the user was saved and a welcome email was sent. Those are outputs, just ones that go to other parts of the system.
A mock is a fake that records what it was asked to do, so you can check it afterwards:
expect(emailService.sendWelcome).toHaveBeenCalledWith('a@b.com'); // it was told to send
expect(userRepo.save).not.toHaveBeenCalled(); // it was NOT told to save
A mock is a way to check expected outputs that leave through a dependency.
This only works because registerUser receives the database and email service as arguments instead of creating the real ones itself. In the real app, the real services are passed in. In a test, the fakes are. This is called dependency injection, and it's a big part of what makes code testable.
The full behaviour of registerUser as a tableโ
Put together, testing registerUser is the same "input โ expected answer" idea as the password table, just with more columns:
| Arguments | Stub: email exists? | Expected result | Expected: saved? | Expected: email sent? |
|---|---|---|---|---|
| Valid, age 25 | No | Returns the user | โ Yes | โ Yes |
| Valid, age 18 | No | Returns the user | โ Yes | โ Yes |
| Valid, age 17 | โ | Error: must be 18 or older | โ No | โ No |
Email abc | โ | Error: invalid email | โ No | โ No |
| Valid, age 25 | Yes | Error: already registered | โ No | โ No |
Every row is one test. The arguments and stubs are the inputs. The return value and mock checks are the expected answers. And every expected answer was decided from the requirement, before the code ran.
Here's how the duplicate-email row looks as a real test. It follows the standard three-step shape, Arrange, Act, Assert:
test('does not save or email a user whose email already exists', async () => {
// Arrange: the stub says this email is taken
userRepo.findByEmail.mockResolvedValue({ id: 1 });
// Act + Assert: registering should fail with the right error
await expect(
registerUser({ email: 'a@b.com', age: 25 }, { userRepo, emailService })
).rejects.toThrow('Email already registered');
// Assert: nothing was saved, no email was sent
expect(userRepo.save).not.toHaveBeenCalled();
expect(emailService.sendWelcome).not.toHaveBeenCalled();
});
Each test gets brand-new fakes before it runs, so one test can never affect another. That's what people mean when they say unit tests are isolated: isolated from the outside world by the fakes, and isolated from each other by starting fresh every time.
Unit testing is always the same idea: chosen inputs in, expected answers checked. Stubs and mocks just let you do that for inputs and outputs that travel through other parts of the system.
Where Unit Tests Live and How They Runโ
Unit tests live in the same project and repository as the code, usually in a file right next to the code they test, or in a matching tests folder:
src/
registerUser.js โ the code
registerUser.test.js โ its unit tests
They're not a separate project, because the tests need to load the real code to test it. The file name matters: the framework finds tests by naming patterns like *.test.js (Jest), test_*.py (pytest) or *Test.java (JUnit). Test files are left out of the production build, so users never download them.
One command runs every test in the project, whether that's 5 tests or 5,000, for example npm test, pytest or mvn test. The framework's test runner finds every test file, runs the tests (often several at once, which is safe because each test is isolated), and gathers the results into one report:
FAIL src/registerUser.test.js
registerUser
โ registers a valid new user (4 ms)
โ rejects an invalid email (1 ms)
โ rejects a user aged 17 (1 ms)
โ accepts a user aged exactly 18 (2 ms)
โ does not save or email a user whose email already exists (2 ms)
โ registerUser โบ accepts a user aged exactly 18
Expected: registration to succeed
Received: Error "User must be 18 or older"
Tests: 1 failed, 4 passed, 5 total
Time: 0.6 s
The output shows each test as passed (โ) or failed (โ), and for each failure, what was expected vs what actually happened. Here the boundary is wrong: the code probably says age <= 18 where it should say age < 18. The developer catches it seconds after writing it, before anyone else sees it.
Unit tests also run automatically in the CI pipeline. Tests aren't hosted anywhere special. On every push or pull request, a CI server such as GitHub Actions, GitLab CI or Jenkins downloads the repository onto a clean machine and runs the same test command. If any test fails, the pipeline goes red, and most teams block the change from being merged until it's fixed.
| Tool | Its job | Examples |
|---|---|---|
| Testing framework | Writing tests, assertions, the test runner, often fakes too | Jest, pytest, JUnit |
| Mocking library | Creating stubs and mocks, where the framework doesn't include it | Mockito (Java) |
| Coverage tool | Showing which lines of code the tests ran | Built into Jest; JaCoCo, coverage.py |
| CI server | Running all tests automatically on every change | GitHub Actions, GitLab CI, Jenkins |
- A unit is the smallest piece of code that does one job, usually a function or method.
- Unit testing checks each unit on its own, from the inside, using code instead of clicks.
- Each test pairs chosen inputs with expected answers decided from the requirement. Stubs feed in hidden inputs and mocks check hidden outputs.
- Unit tests are fast and automatic, and they point to exactly what broke.
- They act as a safety net, so code can keep changing without old features quietly breaking.
- Manual testing checks the user experience, and unit tests check the pieces. You need both.
Where to Go Nextโ
- Ready to pick a framework? Read How to Choose a Unit Testing Framework.
- Once your app is split into services, read What Is Contract Testing?.
- Some automated tests pass and fail at random. What Are Flaky Tests? explains why and how to fix them.