When testing code that relies on external services or APIs, it is important to mock or stub these dependencies to ensure reliable and isolated testing. PHPUnit provides various ways to achieve this:
$mock = $this->getMockBuilder(ExternalService::class)
->disableOriginalConstructor()
->getMock();
$mock->method('someMethod')->willReturn('expectedResult');
$stub = $this->getMockBuilder(ExternalService::class)
->disableOriginalConstructor()
->getMock();
$stub->method('someMethod')->will($this->returnValue('expectedResult'));
class MyClass {
private $externalService;
public function __construct(ExternalService $externalService) {
$this->externalService = $externalService;
}
public function myMethod() {
$result = $this->externalService->someMethod();
// ...
}
}
// During testing:
$mock = $this->getMockBuilder(ExternalService::class)
->disableOriginalConstructor()
->getMock();
$myClass = new MyClass($mock);
By using these techniques, you can test your code in isolation without relying on the availability and consistency of external services or APIs, ensuring more reliable and repeatable tests.