CodingNic

Testing and Best Practices

Writing Simple Tests

Testing and Best Practices 28 min read

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

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

Manual Check

python
print(add(2, 3))

If the output is 5, the test passes.

Better: Compare Results

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

result = add(2, 3)

print(result == 5)

Output

text
True

Why This Helps

Instead of only printing values, you directly check if the answer is correct.

Multiple Tests

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

print(add(2, 3) == 5)
print(add(1, 1) == 2)
print(add(0, 5) == 5)

Output

text
True
True
True

Example with Failure

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

print(subtract(5, 2) == 3)

Output

text
False

The test found a bug.

Create Pass / Fail Messages

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

if add(2, 3) == 5:
    print("PASS")
else:
    print("FAIL")

Output

text
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:

python
def square(n):
    return n * n

Write three tests.

Mini Challenge

Create function:

python
def is_even(n):
    return n % 2 == 0

Write tests for:

  • 2
  • 3
  • 0

Expected output:

text
True
True
True

(Each line means the test passed.)

Real World Use Case

Developers write tests for totals, forms, APIs, reports, and calculations.

Quiz

  1. What is a test case?
  2. Why compare actual and expected results?
  3. What does False mean in a test?
  4. 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.