How can I make fun of an external web request in PHPUnit?

I am working on setting up a test kit for testing a PHP Propel project using Phactory and PHPUnit . I am currently trying to execute a unit test a function that makes an external request, and I want to drown out the layout of the response to this request.

Here is a snippet of the class I'm trying to test:

class Endpoint {
  ...
  public function parseThirdPartyResponse() {
    $response = $this->fetchUrl("www.example.com/api.xml");
    // do stuff and return 
    ...
  }

  public function fetchUrl($url) {
    return file_get_contents($url);
  }
  ...

And here is the test function I'm trying to write.

// my factory, defined in a seperate file
Phactory::define('endpoint', array('identifier'  => 'endpoint_$n');

// a test case in my endpoint_test file
public function testParseThirdPartyResponse() {
  $phEndpoint = Phactory::create('endpoint', $options);
  $endpoint = new EndpointQuery()::create()->findPK($phEndpoint->id);

  $stub = $this->getMock('Endpoint');
  $xml = "...<target>test_target</target>...";  // sample response from third party api

  $stub->expects($this->any())
       ->method('fetchUrl')
       ->will($this->returnValue($xml));

  $result = $endpoint->parseThirdPartyResponse();
  $this->assertEquals('test_target', $result);
}

, , getMock, . , fetchUrl , . Phactory endpoint, factory.

? fetch_url $endpoint Endpoint, ?

; unit test , -?

PHPUnit, "Stubbing and Mocking Web Services", 40 , wsdl. , , SO .

, . !!

+5
1

:

  • URL- , , .
  • , . , , " ", , .

, , . Reflections, . , , , .

"" , :

class Endpoint {

    private $dataParser;
    private $endpointUrl;

    public function __construct($dataParser, $endpointUrl) {
        $this->dataPartser = $dataParser;
        $this->endpointUrl = $endpointUrl;
    }

    public function parseThirdPartyResponse() {
        $response = $this->dataPartser->fetchUrl($this->endpointUrl);
        // ...
    }
}

Mock DataParser, , .

: DataParser? , . php, . DataParser , :

class DataParser {
    public function fetchUrl($url) {
        return file_get_contents($url);
    }
}

, -, ​​ "Mock", . url .

+11

All Articles