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
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:
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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.