Having some issues using PHPUnit to test my controllers.
Code I was working on so far was implementing $_POST
or other request variables:
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = array(
'test' => true
);
Most of tests worked perfectly this way until I run into methods that take uses of filter_input_array
function:
$_SERVER['REQUEST_METHOD'] = 'POST';
$_REQUEST = $_POST = $GLOBALS['_POST'] = array(
'test' => true
);
// ....
var_dump(filter_input_array(INPUT_POST));
NULL
I'm not willing to remove filter_input
functions from not mine code, but I'm unable to make them working in tests.
Versionings:
PHP 5.5.9-1ubuntu4.9 (cli) (built: Apr 17 2015 11:44:57)
Apache/2.4.7 (Ubuntu)
PHPUnit 4.6.6 by Sebastian Bergmann and contributors.
Any help will be appreciated.
Setting $_SERVER
with CONTENT_LENGTH
and CONTENT_TYPE
does not fix the problem. My version of PHP does not allow me to write to php://stdin
in way its described in PHP 5.6.0 chagelog (or way I understand it), but file_put_contents(STDIN,..)
succeed but does not work anyway.
Because it is a phpunit test, maybe there is some kind of annotation or phpunit.xml
entry I don't know yet, that may fix this problem in php-cgi POST setting manner.
If the input to filter_input_array
can only be set by the initial request, and not changed at run time, then the only way to still test it is to have a your base test proxy to another test script by making an HTTP request with the right POST data and processing the response.
main_test.php:
<?php
$data = array(
'testname' => 'yourtestname',
'some_post_var' => 'some_value'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://localhost/proxy_test.php");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
if ($response == 'pass') {
// test passed
}
proxy_test.php
<?php
$test_name $_POST['testname']; // what test to run?
$response = run_test($test_name); // run test that uses filter_input_array
if ($response) {
echo "pass"; // used by main_test.php to check if test passed
} else {
echo "fail";
}
It seems like this is a limitation of PHP, filter_input_array()
does not allow a $_POST
array modified at runtime. See this bug for some more information. The workaround is probably to use one of the other filter functions and pass in the $_POST
array yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With