开发者

how do I override php://input when doing unit tests

I'm trying to write a unit test for a controller using Zend and PHPUnit

In the code I get data from php://input

$req = new Zend_Controller_Request_Http();
$data = $req->getRawBody();

My code works fine when I test the real application, but unless I can supply data as a raw http post, $data will always be blank. The getRawBody() method basically calls file_get_contents('php://input'), but how do I override this in order to supply the test data to my appl开发者_开发百科ication.


I had the same problem and the way I fixed it was to have the 'php://input' string as a variable that is settable at run time. I know this does not really apply directly to this question as it would require modifying the Zend Framework. But all the same it may be helpful to someone.

For example:

<?php
class Foo {

    public function read() {
        return file_get_contents('php://input');
    } 
}

would become

<?php
class Foo {

    public $_fileIn = 'php://input';

    public function read() {
        return file_get_contents($this->_fileIn);
    }

}

Then in my unit test I can do:

<?php
$obj = new Foo();
$obj->_fileIn = 'my_input_data.dat';
assertTrue('foo=bar', $obj->read());


You could try mocking the object in your unit tests. Something like this:

$req = $this->getMock('Zend_Controller_Request_Http', array('getRawBody'));
$req->method('getRawBody')
    ->will($this->returnValue('raw_post_data_to_return'));


Provided the $req->getRawBody() is, as you say, the same as file_get_contents('php://input')...

$test = true; /* Set to TRUE when using Unit Tests */

$req = new Zend_Controller_Request_Http();
if( $test )
  $data = file_get_contents( 'testfile.txt' );
else
  $data = $req->getRawBody();

Not a perfect solution, but similar to what I have used in the past when designing scripts to handle piped emails with great success.


Zend_Controller_Request_HttpTestCase contains methods for setting and getting various http request/responses.

For example: $req = new Zend_Controller_Request_HttpTestCase; $req->setCookie('cookie', 'TRUE'); $test = $this->controller->cookieAction($req); $this->assertSame($test, TRUE);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜