Course contentsShow
← Computer Science
Lesson 2227 of 2,87250. Software TestingFree lesson

Test Assertions and Matchers

Explore common assertion methods for equality, truthiness, exceptions, and collections.

Test Assertions and Matchers

You'll learn the essential toolkit for verifying expected outcomes in your unit tests through assertion methods and matcher functions.

What Are Assertions and Matchers?

Assertions are statements in your tests that declare what should be true after your code runs. Think of them as checkpoint inspectors—if reality doesn't match the expectation, the test fails and raises an alarm. Matchers are more sophisticated assertion helpers that make your tests readable and expressive, letting you say things like "this list should contain that item" instead of writing manual loops.

Common Assertion Categories

Equality Assertions

These verify two values are the same:

  • assertEqual(actual, expected) – checks if values are equal
  • assertNotEqual(actual, expected) – checks if values differ

Truthiness Assertions

These test boolean conditions:

  • assertTrue(condition) – verifies something is true
  • assertFalse(condition) – verifies something is false
  • assertIsNone(value) – checks if value is null/None

Exception Assertions

These confirm your code handles errors properly:

  • assertRaises(ExceptionType) – verifies a specific exception is thrown when it should be

Collection Assertions

These work with lists, arrays, and sets:

  • assertIn(item, collection) – checks membership
  • assertNotIn(item, collection) – verifies absence
  • assertEqual(list1, list2) – compares entire collections

Why Matchers Matter

Matchers provide clearer failure messages. Instead of "False != True," a good matcher tells you "Expected list to contain 'apple', but found ['orange', 'banana']." This dramatically speeds up debugging.

Key Takeaway: Assertions and matchers form the vocabulary of testing—they let you precisely express what "correct behavior" means for each unit of code, turning vague expectations into automated verification.