TestCase is the unittest base class for organizing individual tests. Create a subclass, name it with a Test prefix, and add test_ methods whose assertions compare actual results with expected results. section 13.3.2 section 13.5
Listing 13.5 Testing a function using TestCase (test_task_func.py)
from task_func import Task, create_task #1
import unittest #2
class TestTaskCreation(unittest.TestCase): #3
def test_create_task(self):
task_text = "Laundry,3"
created_task = create_task(task_text) #4
self.assertEqual(created_task.__dict__,
Task("Laundry", 3).__dict__)
if __name__ == "__main__":
unittest.main()
A focused example subclasses TestCase, calls create_task, compares object state with assertEqual, and runs the suite through unittest.main(). section 13.3.2
Use TestCase subclasses to:
- Group related tests for a function or class. section 13.3.2 section 13.4.1
- Name runnable methods with the test_ prefix so unittest discovers them automatically. section 13.3.2
- Reuse preparation logic with setUp before each test. section 13.4.1
- Check behavior with assertEqual and related TestCase assertion methods. section 13.5
Running a two-test suite
Executing the test file produces two dots followed by “Ran 2 tests in 0.000s” and “OK”, indicating that both tests passed. section 13.4.1
