Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST parameters to PHPUnit test

Tags:

php

phpunit

I'm new on testing, I'm using PHPUnit to write test. All the site has been designed using the MVC pattern.

I would like to test each method on my controllers, the problem is that such methods receives the parameters though the $_POST variable. How can I overwrite this variable?

Thanks in advance Alejandra

like image 507
Alejandra Avatar asked Apr 27 '10 16:04

Alejandra


People also ask

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

What is a PHPUnit test?

PHPUnit is a unit testing framework for the PHP programming language. It is an instance of the xUnit design for unit testing systems that began with SUnit and became popular with JUnit. Even a small software development project usually takes hours of hard work.

What is assertion in PHPUnit?

The assertion methods are declared static and can be invoked from any context using PHPUnit\Framework\Assert::assertTrue() , for instance, or using $this->assertTrue() or self::assertTrue() , for instance, in a class that extends PHPUnit\Framework\TestCase .


2 Answers

The best approach would be to abstract the Request into a separate class and not access the superglobals at all. This way you decouple the actual server and request environment from the application. You can then mock the Request easily.

like image 153
Gordon Avatar answered Sep 27 '22 21:09

Gordon


First, if you are using Zend_Test, use

$this->request->setMethod('POST')->setPost(array(insert array info here));

If your not using that, try this:

Warning: Not the best solution, but it will work!

Put this in your setUp fixture

 protected function setUp()
    {
        parent::setUp();
        $_POST = array();
    }

Then before you call your test just do something similar to this:

$_POST = array(insert array data here)
like image 22
Enrique Avatar answered Sep 27 '22 22:09

Enrique