Last active
December 1, 2023 14:54
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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