0
0
PythonHow-ToBeginner · 3 min read

How to Use unittest Module in Python: Simple Guide

Use the unittest module in Python by creating a class that inherits from unittest.TestCase, then define test methods starting with test_. Run tests by calling unittest.main() in your script or using the command line.
📐

Syntax

To use unittest, import the module, create a class inheriting from unittest.TestCase, and write test methods starting with test_. Use assertions inside these methods to check expected results. Finally, call unittest.main() to run the 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 shows a simple test case that checks if the sum of two numbers is correct. It demonstrates how to write a test method and run it using unittest.main().

python
import unittest

def add(a, b):
    return a + b

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

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

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

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

Common Pitfalls

  • Not naming test methods starting with test_ so they are not discovered.
  • Forgetting to call unittest.main() to run tests.
  • Using print statements instead of assertions to check results.
  • Not inheriting from unittest.TestCase in your test class.
python
import unittest

# Wrong: test method name does not start with 'test_'
class WrongTest(unittest.TestCase):
    def check_add(self):
        self.assertEqual(1 + 1, 2)

# Right: test method name starts with 'test_'
class RightTest(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1 + 1, 2)

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

Quick Reference

Here is a quick summary of key unittest features:

FeatureDescription
unittest.TestCaseBase class for creating test cases
test_ prefixMethod names must start with 'test_' to be run as tests
assertEqual(a, b)Check if a equals b
assertTrue(x)Check if x is True
assertFalse(x)Check if x is False
unittest.main()Run all tests in the script

Key Takeaways

Create test classes by inheriting from unittest.TestCase.
Name test methods starting with 'test_' for automatic discovery.
Use assertion methods like assertEqual to check expected results.
Run tests by calling unittest.main() in your script.
Avoid using print statements; rely on assertions for testing.