CodingNic

Testing and Best Practices

Assertions in Tests

Testing and Best Practices 32 min read

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.

python
import unittest

class TestDemo(unittest.TestCase):
    def test_add(self):
        self.assertEqual(2 + 3, 5)

assertTrue()

Checks a value is True.

python
class TestDemo(unittest.TestCase):
    def test_true(self):
        self.assertTrue(10 > 5)

assertFalse()

Checks a value is False.

python
class TestDemo(unittest.TestCase):
    def test_false(self):
        self.assertFalse(3 > 10)

assertIn()

Checks if a value exists inside a collection.

python
class TestDemo(unittest.TestCase):
    def test_in(self):
        self.assertIn("a", "cat")

assertIsNone()

Checks value is None.

python
class TestDemo(unittest.TestCase):
    def test_none(self):
        value = None
        self.assertIsNone(value)

Full Example

python
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

text
..
OK

Why Use Different Assertions?

Different checks make tests clearer and easier to understand.

Code Along

Create function:

python
def greet(name):
    return "Hello " + name

Write a test using assertEqual().

Mini Challenge

Create:

python
items = ["Pen", "Book", "Bag"]

Write tests:

  • Check "Book" is in the list
  • Check "Phone" is not in the list
  • Check None is None

Expected output:

text
...
OK

Real World Use Case

Developers use assertions to test forms, APIs, calculations, database results, and business rules.

Quiz

  1. What is an assertion?
  2. Which assertion checks equality?
  3. Which assertion checks membership?
  4. 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.