Sobes.tech
Junior

What is unit testing?

sobes.tech AI

Answer from AI

Unit testing is the process of testing individual, smallest isolated logical blocks of code (modules, functions, methods) in an application.

Main goals of unit testing:

  • Verification of the correctness of each module in isolation.
  • Early detection of defects at the code level.
  • Facilitation of refactoring and code maintenance.
  • Providing documentation on module operation.

Characteristics of unit testing:

  • Performed by developers.
  • Focused on checking the business logic of the module, not on interaction with external dependencies (databases, file systems, networks).
  • Uses test frameworks (JUnit, NUnit, Pytest, Mocha, etc.).
  • Often employs stubs, mocks, or fixtures to isolate the tested module.

Example of a Python unit test using Pytest:

# test_math_functions.py

import pytest
from math_functions import add, subtract

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

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

def test_subtract_positive_numbers():
    # Testing subtraction of positive numbers
    assert subtract(5, 2) == 3

def test_subtract_with_negative_result():
    # Testing subtraction with a negative result
    assert subtract(2, 5) == -3