Sobes.tech
Middle

What is unit testing and why are mock objects needed?

sobes.tech AI

Answer from AI

Unit testing is a method of software testing where the correctness of individual, isolated parts of the code (functions, methods, classes) is verified. The goal is to ensure that each part works correctly independently of the rest of the system.

Mock objects (stubs) are used to simulate the behavior of real dependencies in tests. This allows:

  • Isolating the tested module from external services, databases, network calls.
  • Controlling the behavior of dependencies (e.g., returning specific data or triggering errors).
  • Increasing the speed and reliability of tests by eliminating external factors.

Example of using mock in Python with the unittest.mock library:

from unittest.mock import Mock

def fetch_data(api_client):
    return api_client.get_data()

# In the test
mock_api = Mock()
mock_api.get_data.return_value = {'key': 'value'}
result = fetch_data(mock_api)
assert result == {'key': 'value'}