Tutorial

How To Use unittest to Write a Test Case for a Function in Python

Practical guide to writing a python unittest test case: examples for success and exception tests, using assertRaises, setUp/tearDown, and running via python -m unittest.

Drake Nguyen

Founder · System Architect

3 min read
How To Use unittest to Write a Test Case for a Function in Python
How To Use unittest to Write a Test Case for a Function in Python

Introduction

The Python standard library includes the unittest framework to create and run tests for your code. A well-written python unittest test case helps catch bugs early, prevents regressions, and supports practices like test-driven development. This guide shows how to write simple unit tests in Python, run them from the command line, and use common unittest.TestCase features such as assertions, setUp, tearDown, and exception testing.

Prerequisites

  • Basic knowledge of Python functions and modules.
  • Python 3 installed and available on your PATH so you can run python -m unittest.

Defining a TestCase subclass

To create a test suite with the unittest module, define a class that inherits from unittest.TestCase. Test methods must begin with test. Below is a concise python test case example showing a function and a corresponding unittest test case for a function python:

# test_add_fish_to_tank.py
import unittest

def add_fish_to_tank(fish_list):
    if len(fish_list) > 10:
        raise ValueError("A maximum of 10 fish can be added to the tank")
    return {"tank_a": fish_list}

class TestAddFishToTank(unittest.TestCase):
    def test_add_fish_success(self):
        actual = add_fish_to_tank(["shark", "tuna"])
        expected = {"tank_a": ["shark", "tuna"]}
        self.assertEqual(actual, expected)

This file demonstrates a typical python unittest test case structure: the function under test and a TestCase subclass with an assertion. Use assertEqual, assertTrue, assertFalse, and other assertion helpers to validate behavior.

Executing a TestCase

Run a single test file from the directory containing the file by invoking the library module directly:

$ python -m unittest test_add_fish_to_tank.py

The python -m unittest command discovers and runs tests in the specified file. Passing no arguments runs tests discovered with the default discovery pattern. You can also use python -m unittest discover to run multiple test files in a directory.

Seeing test outcomes

When tests pass, unittest prints dots (.) for successful tests and letters like F for failures. A typical passing output looks like:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

Testing exceptions with assertRaises

You can assert that a function raises an expected exception using assertRaises. This is useful for validating input checks and error handling. Here is a python unittest assertRaises example:

# extend test_add_fish_to_tank.py
class TestAddFishToTank(unittest.TestCase):
    def test_add_fish_success(self):
        actual = add_fish_to_tank(["shark", "tuna"])
        expected = {"tank_a": ["shark", "tuna"]}
        self.assertEqual(actual, expected)

    def test_add_fish_raises_value_error(self):
        too_many = ["shark"] * 25
        with self.assertRaises(ValueError) as ctx:
            add_fish_to_tank(too_many)
        self.assertEqual(str(ctx.exception), "A maximum of 10 fish can be added to the tank")

Using the context manager form of assertRaises lets you inspect the exception object and confirm the message if needed. This pattern supports cases such as python unittest test function raises ValueError.

Using setUp to prepare test resources

When multiple tests share common setup, implement setUp on your TestCase. setUp runs before each test method, ensuring a fresh state for every test.

# test_fish_tank.py
import unittest

class FishTank:
    def __init__(self):
        self.has_water = False

    def fill_with_water(self):
        self.has_water = True

class TestFishTank(unittest.TestCase):
    def setUp(self):
        self.tank = FishTank()

    def test_tank_empty_by_default(self):
        self.assertFalse(self.tank.has_water)

    def test_tank_can_be_filled(self):
        self.tank.fill_with_water()
        self.assertTrue(self.tank.has_water)

Using setUp avoids duplicating initialization code across tests and is common in unit testing python workflows.

Cleaning up with tearDown

Use tearDown when each test needs cleanup, such as removing temporary files or closing network resources. tearDown runs after every test method regardless of success or failure.

# test_advanced_fish_tank.py
import os
import unittest

class AdvancedFishTank:
    def __init__(self):
        self.filename = "fish_tank.txt"
        with open(self.filename, "w") as f:
            f.write("shark, tuna")

    def remove_file(self):
        if os.path.exists(self.filename):
            os.remove(self.filename)

class TestAdvancedFishTank(unittest.TestCase):
    def setUp(self):
        self.tank = AdvancedFishTank()

    def tearDown(self):
        self.tank.remove_file()

    def test_file_written(self):
        with open(self.tank.filename) as f:
            contents = f.read()
        self.assertEqual(contents, "shark, tuna")

Combining setUp and tearDown helps maintain test isolation, an important part of reliable unit test python function suites.

Tips and common assertions

  • Follow the naming convention: test methods must start with test so discovery runs them.
  • Use the many assertions available on unittest.TestCase: assertEqual, assertNotEqual, assertTrue, assertFalse, assertIsNone, assertIn, and others.
  • Run tests from the command line with python -m unittest or use python -m unittest discover to run multiple files.

Conclusion

This article walked through how to write a python unittest test case, run tests using python -m unittest, assert exceptions with assertRaises, and manage setup and teardown. With these patterns you can start adding unit tests to your projects and expand your test suite as your code grows. For more advanced usage, consult the official unittest documentation and explore test discovery options, mocking, and test suites.

Quick search phrases: how to write a test case in python using unittest, python unittest example for testing a function, python unittest setUp tearDown example, run python unittest from command line python -m unittest.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.