Php – File Upload and Unit Testing with Zend Framework


How can one best test a controller action which receives a file upload using Zend_Test_PHPUnit_ControllerTestCase?

Ideally, $this->getRequest()->setPost() would take a filename in the data array, but this does not seem to be supported.

I would be willing at this stage to bootstrap/run my application on the command line and create a request object to pass to the front controller. This would bypass Zend_Test_PHPUnit_ControllerTestCase, but I could subsequently check that the file was uploaded properly through a subsequent $this->dispatch('/some/url') in the ControllerTestCase. However, I am also stumped as to how to get a file into the request object using this method.

The only thing I can think to try right now is to bring up an HTTP server via the command line which points to the app (APPLICATION_ENV='testing') and do a file upload via Zend's Http Client or CURL or something. That doesn't strike me as very elegant.

Anyone else had to deal with this issue?


Best Solution

I would recommend taking a look at the unit tests from the Zend_File_Transfer component. They will be able to offer some insight into this.

Basically, you can manipulate the $_FILES superglobal directly in the setUp() of your unit tests. Next, use mock objects for any external sort of service, otherwise you're not truly unit testing, but integration testing.

I would not worry about testing the actual process of uploading the file. That's the realm of the webserver and the language; what is important is you properly test what you do with a (or no) received file.

But, this all depends on how you are handling your file uploads right now. If you provided some more details on how you handle your file uploads, I may be able to offer more suggestions.