tags:

views:

107

answers:

3

Hi everybody,

I am writing PHPUnit test cases for a web application. As the tests are run within a command line environment, I am mocking a number of predefined variables such as $_POST, $_GET,$_SERVER, etc.. My test has to make sure that my controller class parses properly JSON input (which is sent as raw POST and red through php://input). The question is, how can I manipulate the value of php://input without running a web server?

A: 

I would say you have not separated concerns enough ; the way I see it, you should have :

  • one method that gets raw data from php://input and passes that data to another method
  • the second method that receives a string, and parses it as JSON

Each one of those two methods is responsible of one and only one thing ; this way, you can unit-test.

In your case, you can unit-test the behavior of the second method (the one that actually does the work) -- without depending on where the input comes from.

Pascal MARTIN
A: 

What about moving the reading functionality to a class (or even a closure if you're on PHP 5.3), then just replacing it with a mock instance when testing?

Ignas R
+1  A: 

POST data is whatever is fed to PHP's stdin, subject to the CONTENT_LENGTH environment variable telling PHP how many bytes to read (so to change the post data, you simply pipe in something different)

GET data is whatever is in the QUERY_STRING environment variable.

See this for other environment variables that can be useful to set that are used by PHP to populate things like $_SERVER

Yuliy