Back to Blog

Unittest, assertEqual, setUp & tearDown Explained - Python Unit Testing Tutorial #28

Sandy LaneSandy Lane

Video: Unittest, assertEqual, setUp & tearDown Explained - Python Unit Testing Tutorial #28 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Unittest, assertEqual, setUp & tearDown Explained - Python Unit Testing Tutorial

Unit testing in Python helps automate the verification of code correctness, saving time and reducing human error compared to manual testing. This tutorial introduces the unittest framework, demonstrating how to organize tests in classes, use assertions like assertEqual and assertRaises, and manage test setup and cleanup with setUp and tearDown methods.

Code

import unittest

# Example functions to test
def add(a, b):
  return a + b

def divide(a, b):
  if b == 0:
    raise ValueError("Cannot divide by zero")
  return a / b

# Test class inherits from unittest.TestCase
class TestMathTools(unittest.TestCase):

  # Runs before each test method
  def setUp(self):
    print("Setting up before a test")

  # Runs after each test method
  def tearDown(self):
    print("Cleaning up after a test")

  # Test addition correctness
  def test_add(self):
    self.assertEqual(add(2, 3), 5)  # Check if add(2,3) returns 5

  # Test division by zero raises ValueError
  def test_divide_by_zero(self):
    with self.assertRaises(ValueError):
      divide(10, 0)

if __name__ == '__main__':
  # Run tests with verbose output
  unittest.main(verbosity=2)

Key Points

  • Use unittest.TestCase to group related tests in a class structure.
  • assertEqual verifies expected values, while assertRaises tests for expected exceptions.
  • setUp runs before each test to prepare a fresh environment, and tearDown cleans up afterward.
  • Run tests with python3 -m unittest -v for detailed, verbose output.
  • Automated testing improves code reliability and simplifies catching regressions early.