unittest Basics
unittest Basics
Python includes a built-in testing framework called unittest.
It helps you write automated tests that run many checks quickly.
Instead of manually printing results, tests can verify code for you.
What Is unittest?
unittest is Python’s standard testing library.
It lets you:
- group tests
- compare expected results
- run many tests
- detect failures automatically
Why It Matters
With unittest, you can test code again after changes and make sure old features still work.
Basic Example
Create a file:
test_math.py
Add:
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()
Output Example
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
How It Works
Import unittest
import unittest
Loads the testing tools.
Create Test Class
class TestMath(unittest.TestCase):
Your test class inherits from unittest.TestCase.
Create Test Methods
Methods should start with:
test_
Example:
def test_add(self):
Use Assertions
self.assertEqual(add(2, 3), 5)
Checks actual result equals expected result.
Run Tests
unittest.main()
Runs all test methods.
Multiple Tests
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add_one(self):
self.assertEqual(add(1, 1), 2)
def test_add_two(self):
self.assertEqual(add(0, 5), 5)
if __name__ == "__main__":
unittest.main()
Output Example
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Each dot means one passing test.
Example Failure
self.assertEqual(add(2, 2), 5)
This test fails because the answer should be 4.
Code Along
Create function:
def square(n):
return n * n
Write two unittest tests.
Mini Challenge
Create function:
def is_even(n):
return n % 2 == 0
Write tests for:
2→True3→False
Expected output:
..
OK
Real World Use Case
Developers use unittest for APIs, business rules, utilities, calculations, and backend systems.
Quiz
- What is
unittest? - What must test method names start with?
- What does
assertEqual()do? - What does
unittest.main()do?
Assignment
Create a double(n) function and test it with three unittest test methods.
Summary
You learned how to use Python’s unittest module to create and run automated tests.