Assertions in Tests
Assertions in Tests
Tests need a way to check results automatically.
That is what assertions do.
An assertion compares the actual result with what you expect.
If the check is correct, the test passes.
If not, the test fails.
What Is an Assertion?
An assertion is a statement that checks a condition.
In unittest, assertions are methods such as:
assertEqual()assertTrue()assertFalse()assertIn()assertIsNone()
Why Assertions Matter
Assertions help you:
- verify code behavior
- detect bugs quickly
- test many situations
- trust your code
assertEqual()
Checks two values are equal.
import unittest
class TestDemo(unittest.TestCase):
def test_add(self):
self.assertEqual(2 + 3, 5)
assertTrue()
Checks a value is True.
class TestDemo(unittest.TestCase):
def test_true(self):
self.assertTrue(10 > 5)
assertFalse()
Checks a value is False.
class TestDemo(unittest.TestCase):
def test_false(self):
self.assertFalse(3 > 10)
assertIn()
Checks if a value exists inside a collection.
class TestDemo(unittest.TestCase):
def test_in(self):
self.assertIn("a", "cat")
assertIsNone()
Checks value is None.
class TestDemo(unittest.TestCase):
def test_none(self):
value = None
self.assertIsNone(value)
Full Example
import unittest
def is_even(n):
return n % 2 == 0
class TestEven(unittest.TestCase):
def test_even(self):
self.assertTrue(is_even(4))
def test_odd(self):
self.assertFalse(is_even(3))
if __name__ == "__main__":
unittest.main()
Output Example
..
OK
Why Use Different Assertions?
Different checks make tests clearer and easier to understand.
Code Along
Create function:
def greet(name):
return "Hello " + name
Write a test using assertEqual().
Mini Challenge
Create:
items = ["Pen", "Book", "Bag"]
Write tests:
- Check
"Book"is in the list - Check
"Phone"is not in the list - Check
NoneisNone
Expected output:
...
OK
Real World Use Case
Developers use assertions to test forms, APIs, calculations, database results, and business rules.
Quiz
- What is an assertion?
- Which assertion checks equality?
- Which assertion checks membership?
- Why use different assertion methods?
Assignment
Create a square(n) function and test it using assertEqual() with three values.
Summary
You learned how assertions verify results automatically in Python tests.