Unit Testing Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Unit Testing.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

Unit testing is the practice of testing the smallest useful parts of a program, such as a single function or module, in isolation. A unit test gives known input, checks the output, and helps confirm that the unit still behaves correctly after changes.

Instead of testing the whole machine at once, test each small part separately so failures are easier to find.

Read the full concept explanation →

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

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

Common stuck point: A unit test should focus on one behavior at a time. If it depends on half the program, it is no longer a small isolated test.

Sense of Study hint: Pick one function, choose one clear input, write the expected output first, and then run the function to compare the actual result. Add edge cases after the basic test passes.

Common Mistakes to Watch For

Before you work through the examples, skim the mistake guide so you know which shortcuts and sign errors to avoid.

Worked Examples

Example 1

medium
`clamp(x, lo, hi)` returns xx if loxhilo \le x \le hi, else the nearest bound. Give expected outputs for `clamp(5, 0, 10)`, `clamp(-1, 0, 10)`, `clamp(99, 0, 10)`.

Answer

5, 0, 105,\ 0,\ 10

First step

1
55 is inside [0,10][0,10] so return 55.

See the full worked solution + why-it-works coaching

SetupKey insightWhy it worksCommon pitfallConnection

Unlock answer keys One Family plan — every worked solution, all subjects

Example 2

medium
Design 3 unit tests for `reverse(string)`. List input -> expected pairs covering normal, empty, and palindrome cases.

Example 3

medium
`fizzbuzz(n)` returns 'Fizz' if divisible by 3, 'Buzz' if by 5, 'FizzBuzz' if by both, else the number as string. Give expected outputs for n=3,5,15,7n=3,5,15,7.

Example 4

hard
You write a property-based test asserting that for any list L, `reverse(reverse(L)) == L`. Name two specific edge cases the property already covers without you enumerating them.

Example 5

hard
A test mocks a database to return a fixed user. The test passes, but production breaks when the real DB returns null. What is the lesson, and what additional test category is needed?

Example 6

challenge
Following TDD, you write `assert isPrime(2)==True`, `assert isPrime(4)==False`, `assert isPrime(1)==False`. Describe the red-green-refactor cycle as you implement `isPrime`.

Example 7

challenge
A team measures 'tests added per bug found' as a quality metric. Explain a perverse incentive this creates and a better metric.

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

easy
A unit test for `add(2, 3)` should check that the result equals what value?

Example 2

easy
What is the smallest piece of code a unit test typically targets?

Example 3

easy
A unit test for `isEven(4)` expects `true`. The code returns `false`. What does the test do?

Example 4

easy
Why should a unit test for a pure function NOT depend on a live database?

Example 5

easy
Which test best isolates a bug: A) one big test exercising 10 behaviors, or B) ten small tests, one per behavior?

Example 6

easy
After changing production code, what must you do with the existing unit tests?

Example 7

easy
In the pattern assert(f(x)=y)(f(x) = y), what does yy represent?

Example 8

easy
A test passes whether or not the code is correct because it asserts nothing meaningful. What is this test called?

Example 9

medium
`abs(x)` returns the absolute value. Write three test cases (input -> expected) that cover positive, negative, and the boundary. Give the expected outputs for x = 5, x = -5, x = 0.

Example 10

medium
A bug makes `max(a, b)` return the smaller value. Which single test reveals it: A) max(3, 3) == 3, B) max(2, 7) == 7?

Example 11

medium
A test for `divide(a, b)` only checks `divide(6, 2) == 3`. What important behavior is untested, and which input would test it?

Example 12

medium
A test reads a global counter that earlier tests modified, so it sometimes passes and sometimes fails. What is this problem called, and the fix?

Example 13

medium
`round half up`: `roundHalf(2.5)` should give 3. A test asserts `roundHalf(2.5) == 2`. The code returns 3. Did the test catch a bug, or is the test wrong?

Example 14

medium
To test a function that calls an external payment API, you replace the API with a fake that returns a fixed response. What is this technique called?

Example 15

medium
Tests should be FAST so they run on every change. A test that sleeps 30 seconds for a timer violates this. What testing fix keeps it fast?

Example 16

medium
Function `count(list)` should return list length. Tests cover `[1,2,3] -> 3` and `[5] -> 1` but pass on buggy code that ignores empties. Which test would catch the empty-list bug?

Example 17

medium
A test asserts `sort([3,1,2]) == [1,2,3]` but also that the function printed a log line. Why does asserting on the log line weaken the unit test?

Example 18

challenge
You have functions A and B; B depends on A. A regression appears in B's output. You want a test that pinpoints whether the fault is in A or in B's own logic. How should you structure the tests?

Example 19

challenge
A team has 100% line coverage yet a boundary bug ships. Explain how full line coverage can still miss the bug, and what coverage idea would have caught it.

Example 20

challenge
Following test-driven development, you write `assert factorial(0) == 1` and `assert factorial(5) == 120` BEFORE writing the code. What is the immediate expected result of running these tests, and why is that the point?

Example 21

easy
A unit test for `multiply(4, 5)` should assert the result equals what value?

Example 22

easy
True or False: a passing unit test proves the function is bug-free for every possible input.

Example 23

easy
A test for `isPositive(0)` expects `false`. The code returns `false`. What is the test result?

Example 24

easy
Which is NOT a typical input class to cover when unit-testing a function: (a) typical/happy-path, (b) boundary, (c) error, (d) marketing copy?

Example 25

easy
After fixing a bug, what should a developer add to the test suite to prevent recurrence?

Example 26

easy
A test has the structure: arrange inputs, ____, assert outputs. Fill in the blank.

Example 27

easy
Why are independent tests preferred over tests that depend on each other?

Example 28

medium
`is_leap(year)` is True iff year is divisible by 4 but not 100, unless also divisible by 400. Which test input distinguishes a correct implementation from one that ignores the 100/400 rule: 2024, 2023, or 1900?

Example 29

medium
A test calls a real HTTP API and fails when the network is down. What category of bad test is this?

Example 30

medium
A test imports the internal helper `_normalize()` and asserts on it. The team renames `_normalize()` to `_clean()` during refactor and the test breaks even though behavior is unchanged. What testing principle was violated?

Example 31

medium
A test that creates a temporary file but never deletes it eventually fills the disk in CI. What test-suite property is missing?

Example 32

medium
`average([])` should raise an error rather than divide by zero. Write the assertion shape (in words) that tests this.

Example 33

medium
A test runs 100x slower than the median. What practice helps keep the suite fast?

Example 34

medium
Why is asserting `result == 0.1 + 0.2` against `0.3` in a unit test usually a bad idea?

Example 35

medium
After a refactor, 12 of 50 tests now fail. Before investigating any code, what should you confirm first about the failing tests?

Example 36

hard
A test passes locally but fails 1 in 10 CI runs. Which two changes are most likely to identify and fix the flakiness?

Example 37

hard
Two passing tests assert `divide(6,2)==3` and `divide(9,3)==3`. A bug makes `divide` return `3` for any input. Which single new test would catch this bug most cheaply?

Example 38

hard
Mutation testing changes one operator in your code and reruns the tests. If all tests still pass, what does that suggest about the test suite?

Example 39

hard
A code path has branch coverage 100% but condition coverage 60%. Give a brief example of a bug that branch coverage misses but condition coverage catches.

Example 40

challenge
A unit test suite passes for years, then fails when run on Feb 29. Identify the root cause class and how to fix the test going forward.

Background Knowledge

These ideas may be useful before you work through the harder examples.

testingfunctionedge cases