Writing Simple Tests
Writing Simple Tests
Before using test libraries, it is important to understand the idea of a test.
A simple test checks whether a function returns the correct result.
What Is a Test Case?
A test case includes:
- input
- expected output
- actual result
Example:
- Input:
add(2, 3) - Expected:
5
Example Function
def add(a, b):
return a + b
Manual Check
print(add(2, 3))
If the output is 5, the test passes.
Better: Compare Results
def add(a, b):
return a + b
result = add(2, 3)
print(result == 5)
Output
True
Why This Helps
Instead of only printing values, you directly check if the answer is correct.
Multiple Tests
def add(a, b):
return a + b
print(add(2, 3) == 5)
print(add(1, 1) == 2)
print(add(0, 5) == 5)
Output
True
True
True
Example with Failure
def subtract(a, b):
return a + b
print(subtract(5, 2) == 3)
Output
False
The test found a bug.
Create Pass / Fail Messages
def add(a, b):
return a + b
if add(2, 3) == 5:
print("PASS")
else:
print("FAIL")
Output
PASS
Why Test Different Inputs?
A function may work for one case and fail for another.
Test:
- normal values
- zero
- negative values
- edge cases
Code Along
Create function:
def square(n):
return n * n
Write three tests.
Mini Challenge
Create function:
def is_even(n):
return n % 2 == 0
Write tests for:
230
Expected output:
True
True
True
(Each line means the test passed.)
Real World Use Case
Developers write tests for totals, forms, APIs, reports, and calculations.
Quiz
- What is a test case?
- Why compare actual and expected results?
- What does
Falsemean in a test? - Why test multiple inputs?
Assignment
Create a triple(n) function and write four tests for it.
Summary
You learned how to write simple tests by comparing expected and actual results.