CodingNic

Testing and Best Practices

Debugging Failed Tests

Testing and Best Practices 34 min read

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

python
def add(a, b):
    return a - b

Test:

python
import unittest

class TestMath(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

Example Result

text
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

python
def add(a, b):
    return a + b

Common Reasons Tests Fail

1. Wrong Logic

python
return a - b

instead of:

python
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

python
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

python
def greet(name):
    return "Hi" + name

Test expects:

text
Hi Tom

But actual output becomes:

text
HiTom

Fix:

python
return "Hi " + name

Code Along

Create a broken double(n) function.

Write a test.

Debug and fix it.

Mini Challenge

This code is wrong:

python
def square(n):
    return n * 2

Test:

python
self.assertEqual(square(4), 16)

Tasks:

  • Find the problem
  • Fix the function

Expected output after fix:

text
.
OK

Real World Use Case

Developers debug failing tests in websites, APIs, billing systems, and data pipelines every day.

Quiz

  1. Why is a failing test useful?
  2. What does AssertionError compare?
  3. Name two common causes of failed tests.
  4. 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.