Skip to content

Testing Your Code: Unit Tests and Assertions

Beginning of the lesson

Testing Your Code: Unit Tests and Assertions

Prove your functions work, and keep them working while you refactor

Big idea: A unit test is a tiny program that calls one small piece of your code with known inputs and checks that it produces the expected output. Instead of squinting at the screen and deciding by hand each time whether the result "looks right", you write the check once and let the computer run it for you forever. When a change breaks the behaviour months later, a failing test tells you immediately, on the exact line, instead of a user discovering the bug in production.
By the end you will be able to:
  • write assertions that state, in code, what must be true;
  • structure any test with the Arrange-Act-Assert pattern;
  • deliberately choose the edge cases that are most likely to expose bugs;
  • build a small, framework-agnostic test harness in plain C++ and read its pass/fail report.

You already write multi-function programs. Testing is the professional habit that lets you trust them and change them without fear. It needs no external library to start: standard C++ gives you everything you need.

1. Why bother writing tests?

Testing "by hand", running the program, typing an input, and reading the output, works exactly once. It does not scale, and it never protects you tomorrow. Automated tests give you four concrete benefits:

  • Regression protection. A regression is a bug that reappears in code that used to work. A test that passed yesterday and fails today points at the exact behaviour your change broke.
  • Refactoring safety net. You can restructure code, rename things, split a function, swap an algorithm, and re-run the tests. If they still pass, the observable behaviour is unchanged. This is the single biggest reason experienced engineers write tests.
  • Executable documentation. A good test says "given this input, the answer is that". A new reader learns how the function is meant to be used far faster than from prose.
  • Faster feedback. A test suite runs in milliseconds and checks dozens of cases you would never re-check by hand.
Analogy. A pilot runs the same written checklist before every single flight. It is not that the pilot is forgetful; it is that a fixed, repeatable set of checks catches the one problem a busy human eye would skip. Your test suite is that checklist for your code.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers