Entering test forms in PHPUnit

What is the best way to check $_GET and $_POST inputs in PHPUnit ?

I have a class that sanitizes input and wants to verify that it works correctly when processing dummy data. Is there an easy way to set up form variables in PHPUnit or do I just need to uncheck the secondary class / functions that are passed by the form variables in order to test them indirectly?

+5
php unit-testing phpunit
Sep 25 '08 at 9:37
source share
1 answer

Take a look at the idea of including dependencies . In a nutshell, you should feed your code what it needs, and not get the data it needs ... Here is an example:

example without dependency injection

 function sanitize1() { foreach($_POST as $k => $v) { // code to sanitize $v } } sanitize1(); 

dependency injection example

 function sanitize2(array &$formData) { foreach($formData as $k => $v) { // code to sanitize $v } } sanitize2($_POST); 

See the difference? In your PHPUnit test, you can pass the sanitize2() associative array of your choice; you addicted. While sanitize1() is associated with $_POST . $_POST and $_GET are anyway arrays, so in your production code you can pass $_GET or $_POST to your function, but in your unit tests it will be difficult for you to copy some expected data.

Unit test example:

 function testSanitize() { $fakeFormData = array ('bio' => 'hi i\'m arin', 'location' => 'San Francisco'); sanitize($fakeFormData); // assert something } 
+16
Sep 25 '08 at 22:57
source share
— -



All Articles