Not sure which lesson to do first? Find your level and get a plan →

CS Thinking · Software Design & Development · Grade 9-12

Unit Testing

Unit testing is the practice of testing the smallest useful parts of a program, such as a single function or module, in isolation.

assert(f(x)=y)

Quick Answer

Unit testing is the practice of testing the smallest useful parts of a program, such as a single function or module, in isolation. Each test calls the unit with a fixed input and asserts the exact output, for example assert isLeapYear(2024) == True. Write them as you build each function, cover normal, edge and error cases, and rerun the whole set after every change: a failing test names the function that broke and the input that broke it.

Why This Matters

Unit tests make code safe to change. A project with 200 tests that run in seconds tells you within a minute whether today's edit broke something that worked yesterday (a regression), and points at the exact function. Without them, a small change to a date or price function can quietly break features elsewhere in the program, and you hear about it from users weeks later.

Intuitive Explanation

Take one function, isLeapYear(year). The rule: a year divisible by 4 is a leap year, except years divisible by 100, unless they are also divisible by 400. A unit test gives the function one known input and checks one known answer: isLeapYear(2024) should be True, isLeapYear(2023) False, isLeapYear(1900) False, isLeapYear(2000) True. Four tiny tests, one line each, each aimed at a different part of the rule.

'In isolation' means the test checks only this function, with nothing else that could fail in the way. A test for calculateTax should not need the internet, a database or today's date, because then a failure might mean the Wi-Fi dropped rather than the tax rule is wrong. When a unit does depend on something outside, the test swaps in a fixed stand-in, such as a fake clock that always reads 1 March 2024.

A unit test is not the same as running the app and clicking around. Trying the whole program checks everything together; when the total on a checkout screen is wrong, you still have to hunt through 40 functions for the cause. That whole-program check is integration or system testing, and it matters too, but a failing unit test already tells you where to look. Edge cases are related but different: an edge case is an input worth trying, and a unit test is the automatic check that tries it every time.

Think of it like this. Unit testing is like a cook tasting each component before plating: the sauce, the pasta, the cheese, one at a time. If the finished dish is wrong, the cook already knows which parts are fine. The comparison stops at speed: unit tests rerun every check in seconds after every change, which no cook could do.

Core idea. Small automatic checks make code safer to change.


When to Use

Write unit tests when you have a function with clear inputs and outputs, before changing code that already works, or right after fixing a bug that must not return. Questions that show an assert statement, a test case with an expected output, or a failing test to explain call for unit testing. If the question is about how the whole app behaves for a user, that is system testing; if it is only about which inputs to try, start with edge cases.

Tip. Ask: Is a single function checked on its own by code that gives it a fixed input and expects one exact result?

How to Recognize It

Look at how much of the program a check covers, who or what runs it, and what a failure would tell you.

  1. Does the check call one function or module by itself, with no screens, files or network involved?

    Yes means a unit test. A check that runs several parts together, such as logging in and then loading a profile, is integration testing.

  2. Is the check written as code that compares an actual result with an expected one, such as assert add(2, 3) == 5?

    Yes means a unit test that can run automatically. Trying the program by hand and watching the screen is manual testing, part of the wider practice of Testing.

  3. Is the question about which inputs to choose for the checks?

    Yes means it is about Edge Cases: pick empty, zero, one item and boundary values for the unit tests to cover.

  4. Has a test already failed, and the task is to find out why?

    Yes means you are Debugging now: the failing unit test showed which function and input broke, and debugging finds the faulty line.

Unit Testing vs Testing vs Integration testing vs Debugging

Each of these deals with programs that might be wrong, and a failing unit test usually leads straight into debugging. Ask how much of the program is checked, whether the check is code that runs by itself, and whether you are finding a fault or its cause.

Unit Testing

Meaning
Unit testing checks one function or module on its own, using code that compares its output with the expected value.
Key test
One small part, isolated, checked automatically in seconds.
Example
assert is_leap_year(1900) == False passes only if the century rule is coded.

Testing

Meaning
Testing is the whole practice of running software with known inputs to check its behavior, by hand or with code.
Key test
The general activity, of which unit testing is one kind.
Example
A tester signs up with a new account and checks that the welcome email arrives.

Integration testing

Meaning
Integration testing checks that several parts work correctly together, such as an app, its database and its login service.
Key test
Several parts at once, so a failure does not point to one function.
Example
Placing a test order and checking that stock drops, the payment is recorded and the receipt is sent.

Debugging

Meaning
Debugging is finding and fixing the cause of a fault once a test or a user has shown that it exists.
Key test
Starts after a failure and finds why, not whether, something is wrong.
Example
Stepping through is_leap_year to find the line that forgets the 400-year rule.

Formula & Notation

assert(f(x)=y)
A unit test evaluates a single unit under controlled conditions and checks whether observed behavior matches a specified assertion.

Worked Examples

Example 1 — Test every branch of the leap-year rule

Easy

Write unit tests for isLeapYear(year): a year divisible by 4 is a leap year, except a year divisible by 100, unless it is also divisible by 400. Then find which tests a buggy version, return year % 4 == 0, fails.
Show the steps and the answer
  1. Pick one year for each part of the rule: 2024 (divisible by 4), 2023 (not), 1900 (divisible by 100 but not 400), 2000 (divisible by 400).

    Each test aims at a different branch, so whichever branch is coded wrong has a test that catches it.

  2. Write the expected results from the rule: assert isLeapYear(2024) == True; assert isLeapYear(2023) == False; assert isLeapYear(1900) == False; assert isLeapYear(2000) == True.

    Expected values must come from the rule, not from running the code, or the tests would just copy the bug.

  3. Run the buggy version: 2024 % 4 = 0 gives True (pass); 2023 % 4 = 3 gives False (pass); 1900 % 4 = 0 gives True (fail); 2000 % 4 = 0 gives True (pass).

    Only the 1900 test fails, which points straight at the missing 'divisible by 100' exception.

Answer: Tests: 2024 → True, 2023 → False, 1900 → False, 2000 → True. The buggy version fails only the 1900 test.

Takeaway: Choose one test per branch of the rule and take expected answers from the rule; a failure then names the branch that is wrong.

Example 2 — Which of these is really a unit test?

Standard

A team writes three tests for a shopping app: (a) call applyDiscount(100, 0.2) and expect 80; (b) open the app in a browser, add 3 items, check out, and expect a confirmation page; (c) call getExchangeRate('EUR'), which downloads today's rate from a bank's website, and expect 0.92. Which are good unit tests?
Show the steps and the answer
  1. (a): one function, fixed inputs, an exact expected output, since 100 × (1 - 0.2) = 80.

    It runs in milliseconds and gives the same result every time, so a failure can only mean applyDiscount is wrong. It is a unit test.

  2. (b): it drives the browser, the cart, payment and the confirmation page together.

    That is a system (end-to-end) test. It is valuable, but when it fails you still have to find which part caused it.

  3. (c): the result depends on a website and on today's exchange rate.

    It fails whenever the rate moves or the network is down, even if the code is right. Replacing the download with a stand-in that always returns 0.92 turns it into a unit test of what the function does with that value.

Answer: Only (a) is a good unit test. (b) is a system test, and (c) depends on outside state; it becomes a unit test once the bank download is replaced by a fixed stand-in.

Takeaway: In a unit test, nothing outside the unit should be able to change the result.

Example 3 — Find the mistake: one test checking everything

Application

Jade tests a grades module with a single test: assert letterGrade(95) == 'A' and letterGrade(85) == 'B' and letterGrade(-5) == 'error' and average([90, 80]) == 85. The report says only 'test_grades FAILED', and she spends 20 minutes checking average before discovering that letterGrade(-5) returns 'F'. Find the mistake in how the test is written and correct it.
Show the steps and the answer
  1. Count the behaviours inside the one test: three letterGrade cases and one average case.

    Joined with 'and', any one wrong result fails the whole test, and the report cannot say which one.

  2. Split it into four tests: test_A_grade, test_B_grade, test_negative_score_rejected and test_average_of_two.

    With one behaviour per test, the name of the failing test tells you what broke.

  3. Check each expected value against the rules: (90 + 80) / 2 = 85, so test_average_of_two passes; letterGrade(-5) returns 'F', so test_negative_score_rejected fails.

    The split report now shows one red test, pointing straight at the missing check for negative scores.

Answer: Split the bundled assertion into four separate tests. The report then shows only test_negative_score_rejected failing, which points directly at letterGrade(-5) returning 'F' instead of 'error'.

Takeaway: One behaviour per test, named after that behaviour, so every failure explains itself.

Where You'll See It

  • Checking one Lego part before building the whole set

    A unit test checks one small piece (like a single function) in isolation, the way you'd snap-test one Lego brick rather than waiting to see if the whole castle stands.

  • A spell-checker function

    You write a test that feeds 'teh' into the corrector and asserts it returns 'the'; if a future edit breaks that, the test fails immediately and points right at the function.

  • Catching a regression after editing code

    After you tweak a sorting function, rerunning its unit tests confirms it still sorts correctly; without them, you might not notice you broke it until much later.

Common Mistakes

  1. The slip: A good unit test runs the whole program end-to-end to be thorough.

    Why it's tempting: Testing everything at once feels more complete and realistic.

    Instead: A unit test isolates the smallest useful part (one function or module) with known input and expected output; testing the whole system at once is integration testing, and it makes failures harder to pinpoint.

  2. The slip: One big test that checks many behaviors at once is efficient.

    Why it's tempting: Fewer, larger tests feel like less work to write.

    Instead: Each test should check one behavior, so that when it fails you know exactly what broke; bundling behaviors makes a failure ambiguous.

  3. The slip: If you trust your change, you don't need to rerun the tests.

    Why it's tempting: A small edit feels obviously safe, so rerunning seems like a waste of time.

    Instead: Rerun the unit tests after every change to production code; tests exist precisely to catch the breakages you didn't expect.


Mini Practice

Try these on your own. Tap Reveal when you want to check.

  1. Write three assert statements for is_even(n), including one edge case.

    Hint: Try an even number, an odd number, and zero.

  2. multiply(a, b) was written as a + b by mistake. Which of these tests catch it: assert multiply(2, 2) == 4, assert multiply(3, 1) == 3, assert multiply(0, 5) == 0?

    Hint: Work out what a + b gives for each test.

  3. shipping_cost(weight) returns 5 for up to 2 kg, plus 2 for each extra whole kg. What values complete assert shipping_cost(2) == ? and assert shipping_cost(5) == ?

    Hint: How many kilograms over 2 is 5 kg?

  4. A suite of 40 small tests each checks one behaviour, and a change makes 3 of them fail. Why is this more useful than one giant test that checks all 40 behaviours?

    Hint: What would the giant test tell you when it fails?

  5. Test A calls to_celsius(212) and checks that it returns 100. Test B opens the full app, types 212, clicks Convert and reads the screen. Which is a unit test?

    Hint: Which test isolates one function?

  6. A student's test is assert days_until_friday() == 2. It passed on Wednesday and failed on Thursday. The student says: 'The function broke overnight.' What is really wrong?

    Hint: What outside thing does the function depend on?

Want the full set?

50 practice questions for this concept — free to try, every one with a complete worked solution showing the why, not just the answer.

Frequently Asked Questions

What is test-driven development?

Test-driven development, or TDD, turns the usual order around: you write a failing unit test for the next small piece of behavior first, then write just enough code to make it pass, then tidy the code while the tests keep passing. Repeating this in short cycles means every function has tests from the start, and the tests double as examples of how the code is meant to be used.

How do you unit test a function that uses the internet or a file?

You replace the outside part with a stand-in for the test. Instead of really downloading the weather, the test hands the function a fake response, called a mock or a stub, that always says 18 degrees. The test then checks only your function's own logic, runs in milliseconds, and cannot fail just because the Wi-Fi is down. Checking the real connection is left to integration tests.

If all my unit tests pass, is my program correct?

Not necessarily. Tests only check the cases someone thought to write, so a function can pass ten tests and still fail on an eleventh input, such as an empty list. Passing unit tests also say nothing about whether the parts work together or whether the program does what users need. They do give strong evidence that the tested behavior has not broken since the last change, which is their main job.

What is code coverage?

Code coverage measures how much of a program's code the tests actually run, often as a percentage of lines. If the tests never reach the else branch of an if, coverage shows that branch as untested. High coverage is useful for finding gaps, but it is not proof of correctness, because a test can run a line without checking that its result is right.

Learning Path

Unit Testing

You are here

Next →

Version Control
You need Testing (comparing actual output with expected output), Function (a unit with inputs and a return value) and Edge Cases (the inputs most likely to break it). Unit testing adds small, automatic, isolated checks for each function that rerun after every change. Next, Version Control pairs with it: teams run the unit tests on every commit, so a change that fails one never reaches the main branch.

See Also