I’ve created a PHP class that envelopes filter_input functions to make our developer’s life easier.
To validate an HTML form with url, name and age fields, the code would be like that:
$post = Filter::POST();
if ($post->validate_string('name') && $post->validate_integer('age')) {
$url = $post->sanitize_url('url');
}
It would be the same as:
if (filter_input(INPUT_POST,'name',FILTER_UNSAFE_RAW) && filter_input(INPUT_POST,'age',FILTER_VALIDATE_INTEGER)) {
$url = filter_input(INPUT_POST,'url',FILTER_SANITIZE_URL);
}
Well, I think the code is done and now I would like to create a PHPUnit test for it.
The problem is that I have no idea on how to fake GET/POST data on a PHPUnit method, not for this case.
I don’t need to insert values in $_POST, I need “real” data on it, because filter_input works with the data the script received, not with the actual $_POST superglobal.
I’ve tried using the following PHPT test and PHPUnit method to achieve this, with no success at all:
--TEST--
Generates POST and GET data to be used in FilterTest.php
--POST--
name=Igor&age=20
--GET--
name=Igor&age=19
--FILE--
<?php
echo $_POST['nome'].' = '.$_POST['idade'];
?>
--EXPECT--
Igor = 20
public function testPhpt() {
$phpt = new PHPUnit_Extensions_PhptTestCase('FilterTest_data.phpt', array('cgi' => 'php-cgi'));
$result = $phpt->run();
$this->assertTrue($result->wasSuccessful());
}
EDIT
Original code: http://pastebin.com/fpw2fpxM
Code used for initial testing: http://pastebin.com/vzxsBQWm
(sorry for the portuguese, I know it would be better to code in english, but it’s how things work here where I work. If you really think it’s really needed, I can translate the code).
Any idea on what can I do to test this class?
You can’t fake raw POST data. But the problem lies in your code: it’s not unit-testable. Instead of:
If you had:
Would render your code unit testable and amount to the same thing as your previous code did.
P.S.: FILTER_VALIDATE_INTEGER is not valid. The proper constant for this is FILTER_VALIDATE_INT