Sobes.tech
Junior — Middle

When is it recommended to use mock objects in unit testing to simulate dependencies?

sobes.tech AI

Answer from AI

Mock objects are used in unit tests when it is necessary to isolate the tested component from its dependencies. This is useful if dependencies:

  • Are complex or slow (e.g., database, network).
  • Are unstable or variable.
  • Are difficult to reproduce in a test environment.

Using mocks allows controlling the behavior of dependencies, setting expected responses, and verifying interactions.

For example, if you have a class that calls an external API, in tests you can replace this call with a mock object that returns predefined data, making the test fast and predictable.

In PHP with PHPUnit:

$mock = $this->createMock(ExternalService::class);
$mock->method('fetchData')->willReturn(['key' => 'value']);

$service = new MyService($mock);
$result = $service->process();
$this->assertEquals('expected', $result);