Junior — Middle
When and why are mock objects used in unit testing?
sobes.tech AI
Answer from AI
Mock objects are used in unit testing to isolate the tested component from external dependencies such as databases, web services, or complex objects. This allows testing the logic of a specific module without external influences and makes tests faster and more reliable.
For example, if a class depends on an email sending service, in tests, a mock is used to simulate behavior and verify that the send method was called with correct parameters.
In PHP, built-in PHPUnit features are often used to create mocks:
$mock = $this->createMock(SomeService::class);
$mock->method('send')->willReturn(true);
Mocks help focus on testing specific code, independent of external systems, and simplify debugging.