Sobes.tech
Junior — Middle

What should be done if an external service or resource is called in a unit test?

sobes.tech AI

Answer from AI

When a unit test calls an external service or resource, it is necessary to isolate the test from these external dependencies. This is done using mocking or stubbing — replacing real calls with simulated ones that return predictable results.

This allows:

  • Making tests fast and reliable.
  • Avoiding failures due to external service unavailability.
  • Testing response handling logic without actual calls.

In Python, the unittest.mock library is often used for this purpose:

from unittest.mock import patch

@patch('module.external_service_call')
def test_function(mock_service):
    mock_service.return_value = 'expected result'
    result = function_under_test()
    assert result == 'expected result'

Thus, the real call is replaced with a controlled mock.