CodingNic

Testing and Best Practices

unittest Basics

Testing and Best Practices 34 min read

unittest Basics

unittest Basics

Python includes a built-in testing framework called unittest.

It helps you write automated tests that run many checks quickly.

Instead of manually printing results, tests can verify code for you.

What Is unittest?

unittest is Python’s standard testing library.

It lets you:

  • group tests
  • compare expected results
  • run many tests
  • detect failures automatically

Why It Matters

With unittest, you can test code again after changes and make sure old features still work.

Basic Example

Create a file:

text
test_math.py

Add:

python
import unittest

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

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

if __name__ == "__main__":
    unittest.main()

Output Example

text
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

How It Works

Import unittest

python
import unittest

Loads the testing tools.

Create Test Class

python
class TestMath(unittest.TestCase):

Your test class inherits from unittest.TestCase.

Create Test Methods

Methods should start with:

python
test_

Example:

python
def test_add(self):

Use Assertions

python
self.assertEqual(add(2, 3), 5)

Checks actual result equals expected result.

Run Tests

python
unittest.main()

Runs all test methods.

Multiple Tests

python
import unittest

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

class TestMath(unittest.TestCase):
    def test_add_one(self):
        self.assertEqual(add(1, 1), 2)

    def test_add_two(self):
        self.assertEqual(add(0, 5), 5)

if __name__ == "__main__":
    unittest.main()

Output Example

text
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Each dot means one passing test.

Example Failure

python
self.assertEqual(add(2, 2), 5)

This test fails because the answer should be 4.

Code Along

Create function:

python
def square(n):
    return n * n

Write two unittest tests.

Mini Challenge

Create function:

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

Write tests for:

  • 2 → True
  • 3 → False

Expected output:

text
..
OK

Real World Use Case

Developers use unittest for APIs, business rules, utilities, calculations, and backend systems.

Quiz

  1. What is unittest?
  2. What must test method names start with?
  3. What does assertEqual() do?
  4. What does unittest.main() do?

Assignment

Create a double(n) function and test it with three unittest test methods.

Summary

You learned how to use Python’s unittest module to create and run automated tests.