Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active December 1, 2023 14:54
Show Gist options
  • Save Shelob9/10314a369b4fce08ec052dd0bb031415 to your computer and use it in GitHub Desktop.
Save Shelob9/10314a369b4fce08ec052dd0bb031415 to your computer and use it in GitHub Desktop.
Using pre_http_request filter to mock HTTP request responses in WordPress phpunit test https://github.com/WordPress/wordpress-develop/blob/trunk/src/wp-includes/class-wp-http.php#L240-L262
<?php
class Test extends TestCase {
public function test_function_that_makes_api_request(){
add_filter('pre_http_request', function(){
return [
'body' => [
'id' => 1,
],
'headers' => [
'content-type' => 'application/json',
],
'response' => [
'code' => 201,
],
];
});
$saved = SomeClass::saveAndPingApi();
$this->assertTrue( $saved );
}
public function test_function_that_makes_api_request_with_error(){
add_filter('pre_http_request', function(){
return [
'body' => [
'error' => 'invalid request',
],
'headers' => [
'content-type' => 'application/json',
],
'response' => [
'code' => 400,
],
];
});
$saved = SomeClass::saveAndPingApi();
$this->assertFalse( $saved );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment