Skip to content
PythonTesting, Quality, and Packagingbeginner30 min read

Unit Testing with unittest

Learn to write reliable unit tests with TestCase, assertions, fixtures, exception checks, and automatic test discovery.

In this lesson, you will learn

  • ✓Explain unit testing and why automated tests are useful.
  • ✓Create test classes by inheriting from unittest.TestCase.
  • ✓Write test methods and use common unittest assertions.
  • ✓Run tests with unittest.main() and Python's command-line test runner.
  • ✓Use setUp() and tearDown() to prepare and clean up test fixtures.
  • ✓Test expected exceptions, boundary cases, and invalid inputs.
  • ✓Interpret test failures and distinguish failures from errors.
  • ✓Organize tests so they can be discovered and repeated reliably.

1. What is unit testing?

A unit test checks a small, focused piece of program behavior, such as a function or method. For example, if add(2, 3) should return 5, a unit test can verify that result automatically.

Manual testing means running a program and checking its behavior yourself. Automated testing means writing code that performs those checks for you. Once written, a test can be run again whenever the implementation changes.

Python's unittest framework provides a standard structure for creating and running tests. A test case normally belongs to a class that inherits from unittest.TestCase. Individual test methods use assertions to compare expected and actual results.

Tests do not mathematically prove that a program is correct for every possible input. Good tests cover important normal cases, boundary cases, and failure conditions so that defects are easier to detect.

Test a simple function

Test a simple function
python
import unittest
 
def add(a, b):
return a + b
 
class AddTests(unittest.TestCase):
def test_adds_two_numbers(self):
self.assertEqual(add(2, 3), 5)
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

When run as a script, unittest reports one passing test, similar to:

.
Ran 1 test in 0.000s
1 row returned1 column

OK

add() returns the sum of its arguments. AddTests inherits from unittest.TestCase, which provides test-running behavior and assertion methods. The method name starts with test_, so the standard test loader recognizes it as a test method. self.assertEqual(add(2, 3), 5) passes when the actual return value equals 5. unittest.main() discovers and runs the tests when this file is executed as a script. The exact elapsed time and some runner details can vary by Python version and environment.

Note

The unittest framework is included with Python. You do not need to install it using pip.

2. TestCase, test methods, and test discovery

A test class usually inherits from unittest.TestCase. Each test method describes one behavior that should be checked. Test methods normally begin with the name test_ so that the test loader can discover them.

A test method receives self, just like an instance method in an ordinary Python class. This lets it call assertion methods such as self.assertEqual() and self.assertTrue().

When unittest runs a test class, it creates a test case instance for each test method. Each method is run as an independent test, with setup and cleanup handled according to the test framework's lifecycle.

A method named check_addition() will not normally be discovered as a test because its name does not begin with test_. Use clear, descriptive test names that explain the behavior being checked.

Write multiple test methods

Write multiple test methods
python
import unittest
 
def multiply(a, b):
return a * b
 
class MultiplyTests(unittest.TestCase):
def test_positive_numbers(self):
self.assertEqual(multiply(3, 4), 12)
 
def test_zero(self):
self.assertEqual(multiply(5, 0), 0)
 
def test_negative_number(self):
self.assertEqual(multiply(-2, 3), -6)
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

The test runner reports three passing tests, similar to:

...
Ran 3 tests in 0.000s
1 row returned1 column

OK

The class contains three independent test methods. Each method checks a different input case. The runner normally displays one dot for each passing test at its default verbosity. The number of tests and their pass or fail status matter more than the exact execution time.

Note

A useful convention is one main behavior per test method. A test may contain multiple related assertions, but avoid combining unrelated scenarios into one test.

3. Common assertion methods

An assertion compares an actual result with an expected condition. If the condition is not satisfied, unittest records the test as a failure and reports useful diagnostic information.

Use assertEqual(actual, expected) to compare values, assertTrue(value) and assertFalse(value) to check truth values, and assertIsNone(value) to verify None.

Use assertIn(item, collection) to check membership, assertIsInstance(value, type) to check a value's type, and assertRaises() to verify that an operation raises an expected exception.

Prefer specific assertions over a bare assert statement in a unittest test method. The unittest methods provide structured test reporting and clearer failure messages.

Check several kinds of behavior

Check several kinds of behavior
python
import unittest
 
def find_user(users, username):
return users.get(username)
 
class UserTests(unittest.TestCase):
def test_existing_user(self):
users = {'alex': 22}
self.assertEqual(find_user(users, 'alex'), 22)
 
def test_missing_user(self):
users = {}
self.assertIsNone(find_user(users, 'sam'))
 
def test_username_membership(self):
users = {'alex': 22}
self.assertIn('alex', users)
 
def test_result_type(self):
self.assertIsInstance(find_user({'alex': 22}, 'alex'), int)
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

The test runner reports four passing tests, similar to:

....
Ran 4 tests in 0.000s
1 row returned1 column

OK

The first test checks the value returned for an existing key. The second test verifies that a missing key produces None. The third test checks dictionary membership. The fourth test confirms that the returned value is an integer. Each assertion checks a specific requirement and produces a useful failure if that requirement is violated.

Note

assertEqual() checks value equality. assertIs() checks object identity, so use assertIsNone() or assertIs() when identity is the actual requirement.

4. Testing boundary cases and invalid inputs

A test suite should not only cover typical inputs. It should also cover boundaries and cases where the function must reject input or behave differently.

For a division function, useful cases include ordinary division, negative numbers, division by zero, and the exact type of exception raised for invalid operations.

Tests should reflect the behavior you intend the function to provide. If your function is supposed to reject a zero denominator with ValueError, implement that rule explicitly and test for it rather than relying on Python's default ZeroDivisionError.

When comparing floating-point results, remember that many decimal values cannot be represented exactly in binary floating-point. unittest provides assertAlmostEqual() for comparing values within a suitable tolerance.

Test normal and invalid division

Test normal and invalid division
python
import unittest
 
def divide(a, b):
if b == 0:
raise ValueError('Denominator cannot be zero')
return a / b
 
class DivisionTests(unittest.TestCase):
def test_normal_division(self):
self.assertEqual(divide(10, 2), 5)
 
def test_negative_result(self):
self.assertEqual(divide(-9, 3), -3)
 
def test_zero_denominator(self):
with self.assertRaises(ValueError):
divide(10, 0)
 
def test_fractional_result(self):
self.assertAlmostEqual(divide(1, 3), 0.3333333333, places=7)
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

The test runner reports four passing tests, similar to:

....
Ran 4 tests in 0.000s
1 row returned1 column

OK

The first test checks an ordinary result. The second checks behavior with a negative numerator. The third passes only if divide(10, 0) raises ValueError. The fourth compares the repeating decimal result within the requested decimal-place tolerance. Testing the invalid case ensures the function follows its explicitly chosen error-handling contract.

Caution

assertRaises() passes only when the expected exception occurs in its context. If no exception is raised, the test fails. If a different exception is raised, the test also fails.

5. Testing expected exceptions

Errors and invalid inputs are part of a function's behavior. A good test suite checks whether the correct exception is raised for the right reason.

The context-manager form of assertRaises() is useful when the operation requires multiple statements or when you want to inspect the exception object.

Use assertRaisesRegex() when you need to check that an exception message matches a particular regular-expression pattern. Avoid matching entire messages unnecessarily when small, stable parts are enough.

Place only the operation expected to raise inside the assertRaises() block. If you include unrelated statements, an exception from the wrong statement could make the test pass for the wrong reason.

Check exception type and message

Check exception type and message
python
import unittest
 
def withdraw(balance, amount):
if amount <= 0:
raise ValueError('Amount must be positive')
if amount > balance:
raise ValueError('Insufficient funds')
return balance - amount
 
class WithdrawTests(unittest.TestCase):
def test_rejects_non_positive_amount(self):
with self.assertRaisesRegex(ValueError, 'positive'):
withdraw(100, 0)
 
def test_rejects_insufficient_funds(self):
with self.assertRaisesRegex(ValueError, 'Insufficient funds'):
withdraw(50, 100)
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

The test runner reports two passing tests, similar to:

..
Ran 2 tests in 0.000s
1 row returned1 column

OK

The first test verifies that a zero withdrawal amount raises ValueError with a message containing positive. The second test verifies that withdrawing more than the available balance raises ValueError with the expected message. The exception type and message help distinguish two different invalid-input conditions. Both tests pass because the expected exceptions are raised.

6. setUp(), tearDown(), and test fixtures

A test fixture is the state or set of resources needed to run a test. For example, several tests might need the same starting list or a temporary object.

unittest calls setUp() before each test method and tearDown() after the test method finishes. This makes it possible to prepare fresh test data for each test and clean up resources afterwards.

The framework calls tearDown() after a test method even if that method fails, provided setUp() completed successfully. If setUp() fails, tearDown() is not called for that test.

For many simple tests, creating data directly inside each test method is sufficient. Use shared setup methods when they reduce duplication without making tests harder to understand.

Prepare fresh test data

Prepare fresh test data
python
import unittest
 
class ListTests(unittest.TestCase):
def setUp(self):
self.items = [1, 2, 3]
 
def tearDown(self):
self.items.clear()
 
def test_initial_length(self):
self.assertEqual(len(self.items), 3)
 
def test_append_item(self):
self.items.append(4)
self.assertEqual(self.items, [1, 2, 3, 4])
 
if __name__ == '__main__':
unittest.main()
Output
Result Table

The test runner reports two passing tests, similar to:

..
Ran 2 tests in 0.000s
1 row returned1 column

OK

setUp() creates a new list before each test method. test_initial_length() checks the original list length. test_append_item() modifies its own list and checks the result. tearDown() clears the list after each test. Because each test receives fresh data, one test's changes do not leak into the next test.

Note

For resources that need guaranteed cleanup, consider addCleanup() or a context manager. addCleanup() callbacks run even if setUp() fails after the cleanup callback has been registered.

7. Running tests and organizing test files

You can run a test file directly with python test_example.py when the file contains an appropriate unittest.main() entry point.

You can also use Python's built-in command-line test runner. For example, python -m unittest test_example.py runs tests from a named test file. The command python -m unittest discovers tests according to unittest's discovery rules from the current directory.

A common project layout separates application code from test code. For example, calculator.py can contain the function and test_calculator.py can contain its tests. This keeps tests focused on the public behavior of the application.

Test discovery normally looks for files named test*.py and test methods named test_*. Exact discovery behavior also depends on the current directory, package structure, and the options supplied to the runner.

Example project structure

Example project structure
python
project/
calculator.py
test_calculator.py
Output
A simple project contains calculator.py and test_calculator.py.

calculator.py contains the functions that the application needs. test_calculator.py imports those functions and checks their behavior. Run python -m unittest test_calculator.py from the project directory to run that test module. Run python -m unittest to use the framework's standard test discovery from the current directory.

Note

The code in this example shows two separate files in one illustrative listing. Put the calculator function in calculator.py and the test class in test_calculator.py when using this layout.

8. Understanding test results and good testing habits

A passing test means the assertions made by that test succeeded. A failing test means an assertion did not hold. An error means an unexpected exception occurred while the test was running.

A useful test should fail when the behavior is wrong. If the test only repeats the implementation's logic or checks something unrelated, it may not detect the defect you care about.

Write tests for observable behavior, use descriptive test names, and keep each test understandable. Avoid depending on execution order or shared mutable state between tests.

A test suite should be repeatable. Tests that rely on the current time, network availability, random values, or external services may need controlled inputs, mocks, or dedicated integration tests.

Unit tests are one part of software quality. They complement integration tests, manual exploratory testing, static analysis, and code review.

A failing assertion reveals a defect

A failing assertion reveals a defect
python
import unittest
 
def subtract(a, b):
return a + b # Intentional bug: should subtract
 
class SubtractTests(unittest.TestCase):
def test_subtracts_numbers(self):
self.assertEqual(subtract(8, 3), 5)
 
suite = unittest.defaultTestLoader.loadTestsFromTestCase(SubtractTests)
result = unittest.TextTestRunner(verbosity=0).run(suite)
print('Successful:', result.wasSuccessful())
print('Failures:', len(result.failures))
Output
Successful: False Failures: 1

The subtract() function contains an intentional defect: it adds the arguments instead of subtracting them. subtract(8, 3) returns 11, but the test expects 5. The assertion fails, so the test result is unsuccessful. The final print statements display False and 1. The runner may also write failure details to standard error; the two printed lines shown here are the explicit print output.

Caution

Do not change the expected value just to make a failing test pass. First decide whether the test describes the intended behavior correctly, then fix the implementation or correct the test accordingly.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Naming a test method without the test_ prefix.

Why it happens: The unittest discovery convention looks for test methods whose names begin with test_; other names may not be discovered as tests.

Incorrect Approach
script.py
python
Naming a test method without the test_ prefix.
Correct Solution
script.py
python
Use descriptive names beginning with test_ so the standard unittest loader can discover them.

Key takeaway: Use descriptive names beginning with test_ so the standard unittest loader can discover them.

#2 Using print() instead of an assertion to check behavior.

Why it happens: print() only displays a value and does not cause a test to fail when the value is wrong; use assertions to compare actual and expected behavior.

Incorrect Approach
script.py
python
Using print() instead of an assertion to check behavior.
Correct Solution
script.py
python
Use self.assertEqual(), self.assertTrue(), self.assertIsNone(), or another suitable assertion so failures are reported by the framework.

Key takeaway: Use self.assertEqual(), self.assertTrue(), self.assertIsNone(), or another suitable assertion so failures are reported by the framework.

#3 Testing only one ordinary input.

Why it happens: A single ordinary example may miss boundary conditions, invalid input, and alternate paths, so add representative edge cases.

Incorrect Approach
script.py
python
Testing only one ordinary input.
Correct Solution
script.py
python
Include important boundary cases, invalid inputs, and expected exceptions.

Key takeaway: Include important boundary cases, invalid inputs, and expected exceptions.

#4 Catching every exception inside a test and treating it as success.

Why it happens: A test should fail when an unexpected exception occurs; catching all exceptions and continuing can hide a real defect.

Incorrect Approach
script.py
python
Catching every exception inside a test and treating it as success.
Correct Solution
script.py
python
Use assertRaises() to check the specific exception the operation is expected to raise.

Key takeaway: Use assertRaises() to check the specific exception the operation is expected to raise.

#5 Putting multiple unrelated operations inside an assertRaises() block.

Why it happens: Keep the assertRaises() context focused on the operation expected to raise the exception, or unrelated code may satisfy the assertion accidentally.

Incorrect Approach
script.py
python
Putting multiple unrelated operations inside an assertRaises() block.
Correct Solution
script.py
python
Keep only the operation that should raise the expected exception inside the block.

Key takeaway: Keep only the operation that should raise the expected exception inside the block.

#6 Sharing mutable test data between tests.

Why it happens: Mutable fixtures can leak state between tests; create fresh data for each test or reset shared state explicitly.

Incorrect Approach
script.py
python
Sharing mutable test data between tests.
Correct Solution
script.py
python
Create fresh data in setUp() or within each test method so one test cannot affect another.

Key takeaway: Create fresh data in setUp() or within each test method so one test cannot affect another.

#7 Assuming a test passes just because the script exits without an obvious error.

Why it happens: Use the test runner's summary and exit status to verify the result; a script can run while reporting failures or skipped tests.

Incorrect Approach
script.py
python
Assuming a test passes just because the script exits without an obvious error.
Correct Solution
script.py
python
Check the test runner's summary and exit status, and ensure the intended tests were discovered and executed.

Key takeaway: Check the test runner's summary and exit status, and ensure the intended tests were discovered and executed.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is unit testing?
Answer:
Unit testing checks small, focused pieces of behavior, such as individual functions or methods. It helps detect defects early and makes it easier to verify that code continues to behave as expected after changes.
Q2:What is unittest in Python?
Answer:
unittest is Python's built-in unit testing framework. It provides TestCase, assertion methods, setup and cleanup hooks, test runners, and test discovery.
Q3:What is the role of unittest.TestCase?
Answer:
TestCase provides the structure for defining test methods and includes assertion helpers. Test classes typically inherit from unittest.TestCase so the test runner can discover and execute their test methods.
Q4:What is the difference between a test failure and a test error?
Answer:
A failure normally means an assertion did not hold. An error means an unexpected exception occurred while the test or its setup and cleanup code was running. Both indicate that the test did not complete successfully.
Q5:How do you test that a function raises an exception?
Answer:
Use with self.assertRaises(ExpectedException): around the operation expected to raise. This verifies that the expected exception occurs and that the test fails if it does not.
Q6:What are setUp() and tearDown() used for?
Answer:
setUp() prepares the fixture before each test method. tearDown() performs cleanup after each method, provided setup completed successfully. They help keep tests independent and repeatable.
Q7:Why should tests be independent?
Answer:
Independent tests do not rely on another test having run first or modified shared state. This makes results more repeatable and helps failures identify the actual behavior that is broken.
Q8:How do you run tests with unittest?
Answer:
You can execute a test file directly if it calls unittest.main(), or run python -m unittest test_module.py. Running python -m unittest uses the framework's standard discovery mechanism from the current directory.
Q9:What makes a good unit test?
Answer:
A good unit test has a clear purpose, a meaningful assertion, predictable inputs, and an expected result. It should be easy to understand, independent of unrelated tests, and cover relevant normal, boundary, and error cases.
Q10:Do unit tests guarantee that software is correct?
Answer:
No. Unit tests only check the behaviors and conditions represented by the tests. Strong test coverage reduces risk but should be combined with other techniques such as integration testing, code review, and appropriate static analysis.

Key takeaways

  • Unit tests repeatedly check focused pieces of program behavior.
  • unittest.TestCase provides test methods and assertion helpers.
  • Test methods normally begin with test_ so the default loader can discover them.
  • Use specific assertions to check values, conditions, membership, types, and expected exceptions.
  • Cover normal cases, boundary cases, and invalid inputs.
  • setUp() prepares data before each test, while tearDown() handles cleanup after each test when setup completes successfully.
  • Run tests with unittest.main() or the python -m unittest command.
  • A passing suite indicates that its checks passed, not that every possible defect has been eliminated.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: