Test Behavior with Unit Tests and Assertions
Core idea
A unit test checks a small behavior in isolation. Define a unittest.TestCase method named test_..., arrange inputs, call the subject and assert the expected result. assertEqual reports a mismatch; a TestResult records failures and errors. The examples run individual cases directly to make the output deterministic; unittest discovery normally runs the suite.
import unittestdef remaining(total, used): return max(0, total - used)class StockTest(unittest.TestCase): def test_exact_limit(self): self.assertEqual(remaining(5, 5), 0)r = StockTest('test_exact_limit').run()print(r.testsRun, r.wasSuccessful())The exact limit is a meaningful boundary. The result records one passing case.
Expose a defect
import unittestdef remaining(total, used): return total - usedclass StockTest(unittest.TestCase): def test_over_limit(self): self.assertEqual(remaining(5, 8), 0)r = StockTest('test_over_limit').run()print(r.wasSuccessful(), len(r.failures))The implementation violates the stated nonnegative contract. The failing test is intentional.
Common mistake
Do not compute the expected value using the same implementation under test. Avoid using bare assert for production input validation: optimization can remove it. Test normal, boundary and invalid cases as appropriate.
Practice
Fix the defective function and add a case with no items used. Run both cases with unittest.TestSuite and inspect the result.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Unit tests and assertions
Check your understanding of unit tests and assertions.
What is printed?
import unittestclass T(unittest.TestCase): def test_a(self): self.assertEqual(2+2,4)print(T('test_a').run().wasSuccessful())What is printed?
import unittestclass T(unittest.TestCase): def test_a(self): self.assertEqual(2,3)print(len(T('test_a').run().failures))What makes a useful boundary case?
What should an expected value be based on?