Debugging Failed Tests
Debugging Failed Tests
Sometimes tests fail.
That is normal.
A failing test is useful because it shows something needs attention.
Your job is to read the failure, find the cause, and fix the code.
Why Failed Tests Matter
Failed tests help you:
- catch bugs early
- prevent broken features
- improve code quality
- fix problems faster
Example Failure
def add(a, b):
return a - b
Test:
import unittest
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
Example Result
FAIL: test_add
AssertionError: -1 != 5
How to Read It
The message means:
- actual result =
-1 - expected result =
5
So the function logic is wrong.
Fix the Code
def add(a, b):
return a + b
Common Reasons Tests Fail
1. Wrong Logic
return a - b
instead of:
return a + b
2. Wrong Expected Value
Your test may be incorrect.
3. Typing Mistakes
Wrong variable names or spelling.
4. Edge Cases Missed
The code works for normal values but fails for zero, empty input, or negatives.
Use print() for Debugging
result = add(2, 3)
print(result)
See what the function returns.
Use VS Code Debugger
Set breakpoints and inspect variables line by line.
Test One Problem at a Time
Fix the first failing test, then run tests again.
Example: String Bug
def greet(name):
return "Hi" + name
Test expects:
Hi Tom
But actual output becomes:
HiTom
Fix:
return "Hi " + name
Code Along
Create a broken double(n) function.
Write a test.
Debug and fix it.
Mini Challenge
This code is wrong:
def square(n):
return n * 2
Test:
self.assertEqual(square(4), 16)
Tasks:
- Find the problem
- Fix the function
Expected output after fix:
.
OK
Real World Use Case
Developers debug failing tests in websites, APIs, billing systems, and data pipelines every day.
Quiz
- Why is a failing test useful?
- What does
AssertionErrorcompare? - Name two common causes of failed tests.
- Why fix one failure at a time?
Assignment
Write a wrong function on purpose, create a test, then debug and fix it.
Summary
You learned how to read failing tests, find bugs, and fix code with confidence.