Sobes.tech
Intern

What is a unit test?

sobes.tech AI

Answer from AI

Unit testing is a software testing method where individual, minimal parts of the code (units, usually functions, methods, or classes) are isolated and checked for their expected behavior.

Goals of unit testing:

  • Logic verification: Checking the correctness of a specific piece of code in isolation.
  • Early defect detection: Identifying errors during development when fixing them is cheapest.
  • Facilitating refactoring: Ensuring that changes in the code do not break existing functionality.
  • Documentation: Unit tests can serve as examples of how to use the code.
  • Improving code design: Writing testable code often leads to a more modular and understandable design.

Key characteristics of unit tests:

  • Automation: They are executed automatically by testing frameworks.
  • Isolation: Testing a single unit, minimizing dependencies on external systems (databases, network, file system), often using mocks or stubs.
  • Speed: They should run very quickly so they can be executed frequently (e.g., on every code change or before commit).
  • Determinism: The test result should be the same every time if the tested code has not changed.

Example in Python using pytest:

def add(a, b):
    """Adds two numbers."""
    return a + b

def test_add_positive_numbers():
    # Testing addition of two positive numbers
    assert add(2, 3) == 5

def test_add_negative_numbers():
    # Testing addition of two negative numbers
    assert add(-1, -5) == -6

def test_add_zero():
    # Testing addition with zero
    assert add(0, 7) == 7