Assertion
In short
An assertion is a statement in code declaring that a condition must be true at that point, stopping the test or program with an error if it is false.
What is an assertion in programming and testing?
An assertion is a line of code that states something must be true, such as total == 100 or that a list is not empty. If the condition holds, execution continues silently. If it doesn't, the assertion fails, usually by throwing an error that reports what was expected and what actually happened.
Assertions have two main uses. In tests, they are the assert step of Arrange, Act, Assert: they compare the actual result with the expected one, and a test without assertions only proves that the code didn't crash. Test frameworks and assertion libraries provide helpers such as assert.equal, expect(x).toBe(y), deep equality for objects, and checks that a function throws an error. In production code, runtime assertions document assumptions that must always hold, called invariants, and catch programming mistakes close to where they happen.
An assertion is like a checkpoint on a hiking trail, where the guide confirms everyone is still there before the group continues. Good test assertions are specific, comparing exact values instead of just checking that something is truthy, and they produce failure messages that explain the problem without extra debugging.
Assertions are often confused with input validation. An assertion guards against bugs in your own code, conditions that should be impossible if the program is correct, while validation handles bad data from users or other systems, which is expected and must always be checked. Never rely on assertions to validate user input, because many languages let you switch them off; running Python with the -O flag, for example, removes assert statements entirely.
Key takeaways
- An assertion states a condition that must be true and fails loudly when it isn't.
- In tests, assertions compare actual results with expected results.
- In production code, assertions document invariants and catch bugs early.
- Specific assertions with clear messages make failures easy to diagnose.
- Assertions are not a substitute for validating user input.
Example
def apply_discount(price, percent):
# Runtime assertion: documents an assumption about our own code
assert 0 <= percent <= 100, f"percent out of range: {percent}"
return round(price * (1 - percent / 100), 2)
def test_apply_discount():
# Test assertions: compare the actual result with the expected one
assert apply_discount(80.0, 25) == 60.0
assert apply_discount(19.99, 0) == 19.99Readers ask
What happens when an assertion fails?
The assertion throws an error, such as AssertionError in Python or JavaScript's node:assert module. In a test, the runner marks that test as failed and shows the expected and actual values; in a program, execution stops unless the error is caught.
Should assertions be used in production code?
Yes, for conditions that indicate a bug in your own code, such as an impossible state. Don't use them for user input or other expected errors, which need proper validation and error handling because assertions may be disabled.
See also
- Unit TestTesting & Quality, p. 35A unit test is a small, automated check that verifies one function, method, or class behaves correctly in isolation from the rest of the program.
- Test RunnerTesting & Quality, p. 33A test runner is a tool that finds a project's automated tests, executes them, and reports which ones passed or failed, usually from a single command.
- Test FixtureTesting & Quality, p. 31A test fixture is the known state a test needs before it runs, such as sample data or a configured object, plus the code that sets it up and tears it down.
- Input ValidationSecurity, p. 18Input validation is the practice of checking that data entering a program has the expected type, format and range before it is used, and rejecting the rest.
- ExceptionProgramming Fundamentals, p. 19An exception is an event that interrupts a program's normal flow when an error occurs, which code can catch and handle instead of letting the program crash.
- DebuggingProgramming Fundamentals, p. 15Debugging is the process of finding out why a program misbehaves, locating the faulty code and fixing it, often with the help of a tool called a debugger.
Spotted a mistake or something missing on this page?Suggest an edit