how to unit test curl call in php

后端 未结 6 1451
既然无缘
既然无缘 2020-12-12 20:41

How would you go about unit testing a curl implementation?

  public function get() {
    $ch = curl_init($this->request->getUrl());

    curl_setopt($c         


        
6条回答
  •  误落风尘
    2020-12-12 21:27

    As thomasrutter suggested, create a class to abstract the usage of the cURL functions.

    interface HttpRequest
    {
        public function setOption($name, $value);
        public function execute();
        public function getInfo($name);
        public function close();
    }
    
    class CurlRequest implements HttpRequest
    {
        private $handle = null;
    
        public function __construct($url) {
            $this->handle = curl_init($url);
        }
    
        public function setOption($name, $value) {
            curl_setopt($this->handle, $name, $value);
        }
    
        public function execute() {
            return curl_exec($this->handle);
        }
    
        public function getInfo($name) {
            return curl_getinfo($this->handle, $name);
        }
    
        public function close() {
            curl_close($this->handle);
        }
    }
    

    Now you can test using a mock of the HttpRequest interface without invoking any of the cURL functions.

    public function testGetThrowsWhenContentTypeIsNotJson() {
        $http = $this->getMock('HttpRequest');
        $http->expects($this->any())
             ->method('getInfo')
             ->will($this->returnValue('not JSON'));
        $this->setExpectedException('HttpResponseException');
        // create class under test using $http instead of a real CurlRequest
        $fixture = new ClassUnderTest($http);
        $fixture->get();
    }
    

    Edit Fixed simple PHP parse error.

提交回复
热议问题