问题
I'm covering some legacy code with unit tests. I have some code that looks like this† (I have removed the bits not relevant to this question):
public function search($query) {
$query = urlencode($query);
$url = 'https://example.com/search.php?q=' . $query;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
));
$data = curl_exec($curl);
if (!$data) {
throw new Exception('An error occurred while trying to process the request.');
}
}
How can I force the curl
request to fail so that the Exception
gets throw
n? I'm not allowed to change the existing code in a method until it is fully covered. The URL is hard-coded except for the query string, so I can't change that and the query string is correctly URL encoded with urlencode()
, so I can't pass through a badly formatted string.
Is there a safe string length I could exceed for the query? Perhaps a setting I could change with ini_set()
?
† I'm aware of the bugs in the code
回答1:
cURL favours couple of environmental variables for establishing communications and they can be used to affect curl operation without tweaking tested php code.
These variables are:
- http_proxy
- https_proxy
- no_proxy
So you can preserve the current values of those variables in setUp()
and restore them in tearDown()
.
Following code will break your curl for sure:
putenv("https_proxy=localhost:5678");
putenv("no_proxy=blah-blah-blah");
来源:https://stackoverflow.com/questions/59517271/how-to-force-a-curl-request-in-a-php-method-to-fail-for-a-unit-test