diff --git a/lib/phpunit/classes/advanced_testcase.php b/lib/phpunit/classes/advanced_testcase.php index 7d35aa48622..7f4d92c653d 100644 --- a/lib/phpunit/classes/advanced_testcase.php +++ b/lib/phpunit/classes/advanced_testcase.php @@ -16,6 +16,10 @@ use core\di; use core\hook; +use core\http_client; +use GuzzleHttp\Handler\MockHandler; +use GuzzleHttp\HandlerStack; +use GuzzleHttp\Middleware; /** * Advanced PHPUnit test case customised for Moodle. @@ -878,4 +882,31 @@ abstract class advanced_testcase extends base_testcase { require_once(static::get_fixture_path($component, $path)); } + + /** + * Get a mocked HTTP Client, inserting it into the Dependency Injector. + * + * @param array|null $history An array which will contain the Request/Response history of the HTTP client + * @return array Containing the client, the mock, and the history + */ + protected function get_mocked_http_client( + ?array &$history = null, + ): array { + $mock = new MockHandler([]); + $handlerstack = HandlerStack::create($mock); + + if ($history !== null) { + $historymiddleware = Middleware::history($history); + $handlerstack->push($historymiddleware); + } + $client = new http_client(['handler' => $handlerstack]); + + di::set(http_client::class, $client); + + return [ + 'client' => $client, + 'mock' => $mock, + 'handlerstack' => $handlerstack, + ]; + } }