Tutelage

Lessons › coding and computer science · taught by Leo

Unit testing basics: why small tests help

Learn how unit tests isolate one function, use one input and expected output, and make bugs easier to find.

Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.app

Why unit tests help

Unit tests check one tiny piece of code at a time. That makes bugs easier to find.

Think of it like testing one Lego brick before building the whole model.

If one test fails, you know where to look first.

Big idea: test one job

A unit test should focus on one function, one input, one expected result.

The unit is the smallest job your code does.

A good test gives a known input and checks one expected output.

That way, you know exactly what passed or failed.

Predict a unit test

What is the best thing to test with a unit test?

  1. One small function
  2. The whole app at once
  3. A random screen tap
Show answer

One small function: Yes. A unit test focuses on one small piece.

Worked example: add(2, 3)

Let’s test a simple add function.

First, choose one input, like two and three.

Then write the result you expect, which is five.

The test passes only if the function returns five.

Catch the common mistake

After choosing input add(2, 3), what should you do next?

  1. Write the expected result, 5
  2. Test every function in the app
  3. Guess without checking
Show answer

Write the expected result, 5: Exactly. The next step is to write the expected result.

Why expected beats guessed

A strong test is specific. It knows what should happen.

A weak test is vague. Then you cannot tell what broke.

Specific tests make debugging much faster.

Why isolation matters

If a test fails, isolation helps you know the cause is in that small unit, not hidden somewhere else.

Isolation means fewer moving parts.

Fewer moving parts means fewer places for the bug to hide.

That is why unit tests are so useful when you are debugging.

Watch out: testing too much

A common mistake is testing the whole system in one unit test.

That makes failures hard to understand.

Keep unit tests small and focused.

Your turn: choose a unit test

Which test is the best unit test for a function that doubles a number?

  1. assert double(4) == 8
  2. Open the app and click every button
  3. Check whether the whole website loads
Show answer

assert double(4) == 8: Yes. That checks one function with one clear input and output.

Recap: unit test checklist

Use this checklist on your own.

Pick one unit, one input, and one expected output.

Then assert the result and read the failure if it happens.

Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.app