views:

45

answers:

2

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 application.

+1  A: 

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.

Lucanos
Yeap, not a perfect solution, but how I've decided to implement it too. Thanks.
john ryan
A: 

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'));
Michael
so this would work if I was passing Zend_Controller_Request_Http object into the code I was testing, unfortunately the controller handles all this under the hood. So I think the only way to do it is to change my application to test for the environment I'm in and handle the special case.
john ryan