I understand PHPUnit, I understand how tests are written for methods with parameters, but the question arose how to test methods without parameters, inside which information is taken from $_POST ?

  • You can replace the contents of $ _POST before calling the method being tested. - Arnial

1 answer 1

In a good way, your methods should not interact directly with superglobal arrays ( $_POST , $_GET , $_REQUEST and others). There are a number of reasons for this:

  1. Your code becomes more confusing and not obvious. If the value of the superglobal array changes somewhere in the code, then you will have a "fascinating" debugging session.

  2. Testing code that uses global variables presents certain difficulties and requires additional fuss with setting the correct calling method context.

  3. Using the $_GET and $_POST arrays, you are tightly bound to a specific request format (HTTP requests) and will have to rewrite a lot of code if the external API of your application changes, say, to SOAP.


Nevertheless, code using superglobal variables can still be tested. To do this, PHPUnit leaves you a "loophole": all values ​​of superglobal arrays are copied before running the test suite and are restored at the end of each test method. This is what the PHPUnit documentation says:

By default, the PHPUnit runs your test of changes to global and super-global variables ( $GLOBALS , $_ENV , $_POST , $_GET , $_COOKIE , $_SERVER , $_FILES , $_REQUEST ). Optionally, this can be extended to static attributes of classes.

Thus, you can set the required values ​​of the $_POST array fields in each of the test methods without thinking about the consequences. For example:

 class Controller { public function loadUser() { $user = new \stdClass(); $user->id = (int)$_POST['user_id']; return $user; } } class ControllerTest extends \PHPUnit\Framework\TestCase { public function testUserLoading() { $_POST['user_id'] = 123; $controller = new Controller(); $user = $controller->loadUser(); $this->assertEquals(123, $user->id); } } 
  • Thanks for the answer, I will try, as soon as I free myself , to rewrite methods using $ _POST, etc. - Sirkor