MDL-82627 PHPUnit: Add helper to mock http_client

This commit is contained in:
Andrew Nicols
2024-09-11 11:25:16 +07:00
committed by Huong Nguyen
parent 74d1f5f9ce
commit 3e2d581628
+31
View File
@@ -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,
];
}
}