简体   繁体   English

如何强制 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.');
        }
    }

How can I force the curl request to fail so that the Exception gets throw n?如何强制curl请求失败,以便throw Exception 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.除了查询字符串外,URL 是硬编码的,因此我无法更改它,并且查询字符串是使用urlencode()正确编码的 URL,因此我无法传递格式错误的字符串。

Is there a safe string length I could exceed for the query?是否有我可以超出查询的安全字符串长度? Perhaps a setting I could change with ini_set() ?也许我可以用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. cURL 有利于建立通信的几个环境变量,它们可用于影响 curl 操作,而无需调整已测试的 php 代码。

These variables are:这些变量是:

  • http_proxy http_proxy
  • https_proxy https_proxy
  • no_proxy no_proxy

So you can preserve the current values of those variables in setUp() and restore them in tearDown() .因此,您可以在setUp()保留这些变量的当前值,并在tearDown()恢复它们。

Following code will break your curl for sure:以下代码肯定会打破你的卷曲:

putenv("https_proxy=localhost:5678");
putenv("no_proxy=blah-blah-blah");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM