0
0
PythonHow-ToBeginner · 3 min read

How to Write Unit Test in Python: Simple Guide with Examples

To write a unit test in Python, use the unittest module by creating a class that inherits from unittest.TestCase and define test methods starting with test_. Run tests using unittest.main() to check if your code works as expected.
📐

Syntax

Use the unittest module by importing it. Create a class that inherits from unittest.TestCase. Define test methods starting with test_. Use assertion methods like assertEqual to check expected results. Call unittest.main() to run tests.

python
import unittest

class MyTest(unittest.TestCase):
    def test_example(self):
        self.assertEqual(1 + 1, 2)

if __name__ == '__main__':
    unittest.main()
Output
Ran 1 test in 0.000s OK
💻

Example

This example tests a simple function add that adds two numbers. The test checks if the function returns the correct sum.

python
import unittest

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

class TestAddFunction(unittest.TestCase):
    def test_add_positive_numbers(self):
        self.assertEqual(add(2, 3), 5)

    def test_add_negative_numbers(self):
        self.assertEqual(add(-1, -1), -2)

    def test_add_zero(self):
        self.assertEqual(add(0, 5), 5)

if __name__ == '__main__':
    unittest.main()
Output
Ran 3 tests in 0.000s OK
⚠️

Common Pitfalls

Common mistakes include forgetting to prefix test methods with test_, which causes tests not to run. Another is not using assertion methods, so tests don't check results properly. Also, not calling unittest.main() will prevent tests from running when the script is executed.

python
import unittest

class WrongTest(unittest.TestCase):
    def example(self):  # Missing 'test_' prefix
        self.assertEqual(1 + 1, 2)

if __name__ == '__main__':
    unittest.main()

# Corrected version:

class CorrectTest(unittest.TestCase):
    def test_example(self):  # Correct prefix
        self.assertEqual(1 + 1, 2)
Output
Ran 0 tests in 0.000s OK
📊

Quick Reference

Here is a quick cheat-sheet for writing unit tests with unittest:

ActionCode Example
Import unittest moduleimport unittest
Create test classclass MyTest(unittest.TestCase):
Define test methoddef test_something(self):
Check equalityself.assertEqual(a, b)
Check true conditionself.assertTrue(condition)
Run testsunittest.main()

Key Takeaways

Use unittest.TestCase and prefix test methods with test_ to write unit tests.
Use assertion methods like assertEqual to verify expected outcomes.
Always call unittest.main() to run your tests when executing the script.
Forget the test_ prefix and tests won't run, so name methods carefully.
Keep tests small and focused on one behavior for clarity and reliability.