Sobes.tech
Junior — Middle

Explain what Mock objects are in the context of automated testing?

sobes.tech AI

Answer from AI

Mock objects are special objects used in automated testing to simulate the behavior of real components or dependencies. They allow isolating the code under test from external systems, controlling input data, and verifying interactions.

For example, if a function depends on calling an external API, instead of making a real call, a Mock can be used to return a pre-defined response, which speeds up tests and makes them more reliable.

Example in Python using unittest.mock:

from unittest.mock import Mock

def get_user_name(user_service, user_id):
    return user_service.get_name(user_id)

mock_service = Mock()
mock_service.get_name.return_value = 'Ivan'

assert get_user_name(mock_service, 123) == 'Ivan'
Explain what Mock objects are in the context of… - sobes.tech