如何强制PHP方法中的curl请求因单元测试而失败 [英] How to force a curl request in a PHP method to fail for a unit test
问题描述
我将在单元测试中介绍一些旧代码。我有一些看起来像这样的代码†(我已删除了与该问题无关的位):
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.');
}
}
如何强制 curl
请求失败,以使 Exception
引发 throw
n?在完全覆盖之前,不允许在方法中更改现有代码。除查询字符串外,URL都是硬编码的,因此我无法更改它,并且查询字符串已正确地由 urlencode()
进行URL编码,因此我无法通过格式错误的字符串。
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.
是否存在可以查询的安全字符串长度?也许我可以使用 ini_set()
更改的设置?
Is there a safe string length I could exceed for the query? Perhaps a setting I could change with ini_set()
?
†代码中的错误
推荐答案
cURL支持使用几个环境变量来建立通信,它们可以用来影响curl操作,而无需调整已测试的php代码。
cURL favours couple of environmental variables for establishing communications and they can be used to affect curl operation without tweaking tested php code.
这些变量是:
- http_proxy
- https_proxy
- no_proxy
因此您可以在 setUp()
中保留这些变量的当前值,并在 tearDown()
中恢复它们。
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");
这篇关于如何强制PHP方法中的curl请求因单元测试而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!