How to force a curl request in a PHP method to fail for a unit test

吃可爱长大的小学妹 提交于 2020-02-06 23:59:13

问题


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 thrown? 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!