Skip to content
BENIBIX Learn

Assertion

Development🧪 Testing & QualityTest Basics

Also known as Assert, expect

A line in a test that says what must be true, or the test fails.

Think of it like

Think of it like a scale. You say the box weighs 5 kilos, then you weigh it.

Example

Emma's test asserts that the total is 6. It is really 5, so pytest prints assert 5 == 6 and marks the test failed.

Why it matters

Assertions are what make a test a test. They turn running code into checking code.

Definition

An assertion is a line in a test that states what must be true. If it is true, the test goes on. If it is false, the test stops and fails, and shows what it got instead. In Python it is written with assert; in JavaScript it is often expect. A test with no assertion checks nothing, even when it passes.

Example code

console
$ pytest -q test_fail.py
E       assert 5 == 6
FAILED test_fail.py::test_total - assert 5 == 6
1 failed in 0.03s
The assertion expected 6, got 5, and the test failed.

Common mistake

Writing a test that runs code but asserts nothing. It always passes and catches no bugs.

Key takeaways

  1. 1
    States what must be true. The expected result.
  2. 2
    False means fail. And it shows what it got.
  3. 3
    No assertion, no test. It checks nothing.