how to unit test curl call in php

后端 未结 6 1457
既然无缘
既然无缘 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:08

    One approach to this involves replacing the interface you are using (in this case, the curl_ functions) with dummy versions of themselves which return certain values. If you were using an object-oriented library this would be easier because you could just substitute an dummy object which has the same method names (and indeed, frameworks like simpletest can set up dummy object methods easily). Otherwise, perhaps there is some other sorcery you can use to override built-in functions with dummies. This extension includes override_function() which looks like what you'd need, though that would add another dependency.

    If you want to test this without replacing the curl_ functions with dummy versions, it looks like you will need to set up a dummy server that will return a certain result, so that you can test the way your PHP, and its curl extension, handles that result. To fully test it, you'd need to access this over HTTP rather than, say, a local file, because your PHP depends on having an HTTP response code, etc. So your tests will need a functioning HTTP server.

    Incidentally, PHP 5.4 will actually include its own web server which would come in handy for this purpose. Otherwise, you could put a test script on a known server which you control, or distribute a simple server config with your tests.

    If you were to actually use the live server for your testing, this would become less of a unit test and more of an integration test, because you be testing both your PHP and the server, and the integration between the two. You would also miss out on being able to test on demand how your code handles certain failures.

提交回复
热议问题