Intro to Testing: Unit Tests & TDD

60 min1 pages

What is Intro to Testing: Unit Tests & TDD?

Learning concept: Intro to testing: writing simple unit tests with unittest (or pytest basics) and the value of test-driven thinking

~60 min1 pages
PythonProgrammingBeginner

Unit testing is a disciplined practice where individual components of a software system are tested in isolation to ensure they behave as intended. In Python, two popular approaches are the built-in unittest framework and the more flexible pytest. This page introduces the core ideas behind unit testing and why it matters. You’ll learn how tests act as a safety net that catches regressions when you refactor code, add new features, or optimize algorithms. Tests serve as living documentation, showing how functions and classes are expected to be used and what outcomes are considered correct. A well-structured test suite helps you resist the temptation to rush changes that break existing behavior. The testing mindset is closely tied to the concept of test-driven thinking: writing tests before or alongside your code can guide design decisions, reveal edge cases, and establish clear acceptance criteria. We’ll explore both unittest and pytest basics, comparing their styles and ergonomics to help you choose a workflow that fits your project. As you read, imagine a simple calculator module with add, subtract, multiply, and divide functions. What should each function do if given zero, negative numbers, or decimal values? How would you verify these behaviors with small, focused tests? The value of test-driven thinking becomes apparent when you attempt to extend functionality; tests remind you of the contracts your code must maintain and provide a quick feedback loop for correctness.

Which statement best describes the primary goal of unit tests in a software project?

To test the user interface for aesthetics
To verify that individual components work correctly in isolation
To run the entire system in production to find performance issues
To replace the need for manual debugging

Sign up to unlock quizzes

Example: A simple test file (unittest style)

python
import unittest

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

def subtract(a, b):
    return a - b

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

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

The _____ keyword is used to run all tests from a Python file when using the unittest framework.

Type your answer...

Sign up to unlock quizzes

In pytest, what is the typical way to write a simple test function?

Create a class with methods named test_...
Write a function whose name starts with test_ and use plain asserts
Use a GUI tool to define expected outcomes
Place tests in a separate language file

Sign up to unlock quizzes

Example: Pytest style test function

python
def multiply(a, b):
    return a * b

def test_multiply():
    assert multiply(3, 4) == 12
    assert multiply(-1, 5) == -5

What is a key benefit of test-driven development (TDD) in relation to design?

It delays writing tests until after features are built
It forces you to think about how to use a function before implementing it
It discourages refactoring because tests lie
It replaces the need for code reviews

Sign up to unlock quizzes

Example: Test-driven approach in steps

1) Write a failing test for intended behavior (RED). 2) Implement the minimal code to pass the test (GREEN). 3) Refactor while keeping tests green. This cadence clarifies requirements and prevents over-engineering early.

In unittest, assertion that two values are equal typically uses self.___ assert, while in pytest you simply use the _____ statement.

Type your answer...

Sign up to unlock quizzes

Example: Writing a test first (RED-GREEN-REFACTOR)

python
# RED: failing test
import unittest

def divide(a, b):
    return a / b

class TestDivide(unittest.TestCase):
    def test_divide_by_non_zero(self):
        self.assertEqual(divide(10, 2), 5)

# GREEN: implement minimal function to pass test
# (Nothing more than divide as defined above passes this test)

Which scenario demonstrates a clear benefit of isolating unit tests?

Testing a random integration of modules in production
Verifying the behavior of a small function without dependencies
Measuring system-wide performance under load
Evaluating UI layout in a browser

Sign up to unlock quizzes

Practice: Refactoring with tests

python
def format_price(n):
    return f"${n:.2f}"

# Before refactor: ensure tests cover formatting edge cases

def test_format_price():
    assert format_price(3) == '$3.00'
    assert format_price(3.5) == '$3.50'

# If we later change to handle currencies, tests guard backward compatibility.

Related Topics