Test Classes & TestCase
In unittest, tests are organized into classes that inherit from unittest.TestCase.
Each test class groups related test methods together, making your test suite organized and readable.
Creating a Test Class
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('hello'.upper(), 'HELLO')
def test_isupper(self):
self.assertTrue('HELLO'.isupper())
self.assertFalse('Hello'.isupper())
if __name__ == '__main__':
unittest.main()
Rules for Test Classes
- The class must inherit from
unittest.TestCase. - Class names should start with
Test(e.g.,TestLogin). - The class must not have an
__init__method. - Test methods inside must start with
test_.
Multiple Test Classes
import unittest
class TestUserCreation(unittest.TestCase):
def test_create_user(self):
user = {"name": "Alice", "age": 30}
self.assertIn("name", user)
class TestUserDeletion(unittest.TestCase):
def test_delete_user(self):
users = []
users.append("Alice")
users.remove("Alice")
self.assertEqual(len(users), 0)
if __name__ == '__main__':
unittest.main()
Key Takeaway
Every test must live inside a class that inherits from unittest.TestCase.
This provides all the assertion methods and lifecycle hooks you need.