mirror of
https://github.com/moodle/moodle.git
synced 2025-03-13 20:26:32 +01:00
MDL-82627 PHPUnit: Add helper to mock http_client
This commit is contained in:
parent
74d1f5f9ce
commit
3e2d581628
@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user