๐งช Introduction to Unit Testing in Python
Unit testing is a fundamental practice in software development that helps ensure your code works correctly and remains reliable as it grows and changes.
๐ก What is Unit Testing?
Unit testing is the process of testing small, isolated pieces of code—called units—to verify that each one behaves as expected.
A unit is usually a single function, method, or class.
For example:
Testing a function that adds two numbers.
Testing a method that calculates a user’s discount in an e-commerce app.
The main goals are to:
Catch bugs early.
Ensure code changes don’t break existing functionality.
Improve confidence in your codebase.
๐งฐ Python’s unittest Framework
Python includes a built-in module for unit testing called unittest
.
It provides:
A structure for writing and running tests.
Assertions to check expected outcomes.
Test discovery and reporting tools.
๐ง๐ป Basic Example
Let’s start with a simple function and a unit test for it.
Example Code (calculator.py)
def add(a, b):
return a + b
Example Test (test_calculator.py)
import unittest
from calculator import add
class TestCalculator(unittest.TestCase):
def test_add(self):
result = add(2, 3)
self.assertEqual(result, 5)
if __name__ == '__main__':
unittest.main()
Run the test:
python -m unittest test_calculator.py
✅ Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
⚙️ Common unittest Assertions
Assertion Method Description
assertEqual(a, b) Checks that a == b
assertNotEqual(a, b) Checks that a != b
assertTrue(x) Checks that x is True
assertFalse(x) Checks that x is False
assertIsNone(x) Checks that x is None
assertIn(a, b) Checks that a is in b
assertRaises(Exception, func, *args) Checks that func raises an exception
๐งฉ Structuring Tests
Typically, you organize tests in a tests/ folder at the root of your project:
my_project/
│
├── calculator.py
├── other_module.py
└── tests/
├── test_calculator.py
└── test_other_module.py
You can run all tests at once with:
python -m unittest discover
๐ Beyond unittest
While unittest is great, many developers use pytest
for a simpler, more powerful testing experience:
Less boilerplate code
Better error output
Rich plugin ecosystem
Example using pytest:
from calculator import add
def test_add():
assert add(2, 3) == 5
Run with:
pytest
๐งญ Summary
Concept Description
Purpose Test small parts of your program (functions/classes).
Tool Built-in unittest module (or external pytest).
Benefits Catch bugs early, ensure reliability, enable refactoring safely.
Best Practice Write tests alongside your code and automate them (e.g., in CI/CD).
Learn Fullstack Python Training in Hyderabad
Read More
Testing and Debugging in Python
How to Test Your API Endpoints in Python
Building Versioned APIs in Python
How to Handle Errors and Responses in Full Stack Python APIs
At Our Quality Thought Training Institute in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments