PHPUnit - test MVC controller with $_POST variable

柔情痞子 提交于 2019-11-30 13:57:54

First of all, if you are testing all the way from receiving the POSTed data to checking values in the database, this is not unit-test anymore : you are not testing one component in isolation of the others, but you are testing the integration of those components together.

It makes things harder to test :

  • you have to provide data in harder ways : not just as parameters to a method, but as parameters to your whole application (which means forging POST data, here, for instance)
  • you have more things to verify : not just the return value of a method, or if it threw an exception
  • you have several different and maybe unrelated things that can cause a failure (problem in some PHP code, problem in the database, database server not being available, ...), which will make failures harder to track down to find their cause.


Note that I didn't say that kind of "integration" tests is not useful, btw ;-)


Still, forging the $_POST array is quite simple : it is not read-only, and you can store whatever you want in it.

So, at the begining of your test-case, nothing prevents you from injecting any data you need in it.

What Pascal said. Also, note that there are tools specifically for testing interaction on the http/browser level. You can use SimpleTest's web test cases (Uses an emulated/scriptable browser). If you prefer PhpUnit, I think you can fairly easily use SimpleTest's browser from within PhpUnit. Otherwise there is the more heavy-weight Selenium IDE, for which PhpUnit has integration.

Well you need to do is just set the post var like this.

$this->reques ->setMethod('POST') ->setPost(array( 'param1' => 'value1', 'param2' => 'value2' ));

I hope that works for you

Keep Smile Kdecom

user367134

I agree with Pascal that $_POST array is not a read only array and you can manipulate it as required. Also it depends on your framework, Zendframework provides the freat flexiblility to manipulate the variables as in the example in the link

http://xebee.xebia.in/2010/02/05/test-driven-development-with-zend-framework-and-phpunit/comment-page-1/#comment-3431

But here you loose the advantage of Using PHPUnit's in built function like (assertions, dataprovider, etc) But in most of our case we Use global arrays $_POST, $_GET, or $_REQUEST and when we see PHPUnit examples, we google "How to set POST variables in PHPUnit" As the PHPUnit does not demostrate MVC test case(that's bit of spoon feeding though) We need to get the instance of our framework and then we can play around our framework and PHPUnit Also your way of testing will be different other's way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!