Skip to content

Testing & QA

Assertions (Building Your Own assertEqual)

The idea, in plain English

An assertion is a line that says 'this MUST be true — if it isn't, stop and shout'. It's like the bouncer at the door of your test: if reality doesn't match the claim, it refuses to let the test quietly pass. Real testing libraries give you ready-made assertions like `assertEqual`, but underneath they're just a simple check: compare two values, and if they differ, throw an error with a helpful message.

How it works

  1. 1Write a function that takes the actual value, the expected value, and a short message.
  2. 2Compare them. If they're equal, all is well — the assertion passes quietly.
  3. 3If they differ, 'throw' an error (raise an alarm) that carries the message plus both values, so you can see exactly what was off.
  4. 4Wrap each test in a try/catch so one failing assertion is reported as a FAIL instead of crashing the whole run.

When you'd use it

You reach for assertions inside every test you write — they are the sentence that actually does the checking. Understanding that they're just 'compare and throw' demystifies every testing library you'll ever use.

Common beginner mistakes

  • Writing an assertion with no message. When it fails six months later, 'AssertionError' alone tells you nothing — a message like 'hi becomes HI' tells you exactly what broke.
  • Asserting several unrelated things in one test. When it fails you can't tell which claim broke; keep each test focused on one clear expectation.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
OK: hi becomes HI
PASS uppercase works
FAIL broken expectation -> Assertion failed: 2 + 2 is 5 (expected 5, got 4)

Not sure this is the right topic? See the learning paths → or where this leads →