Sobes.tech
Junior — Middle

How can you verify the correctness of a function using unit testing?

sobes.tech AI

Answer from AI

To verify the correctness of a function using unit testing, it is necessary to:

  1. Write tests that call the function with different input data.
  2. Check that the function returns expected results or correctly changes the state.
  3. Use testing frameworks, such as unittest or pytest in Python.

Example of a simple test using pytest:

import pytest

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


def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0
    assert add(0, 0) == 0

If all assertions pass, it means the function works correctly for these cases. Unit tests help quickly identify errors when code changes.