开发者

how to test a function with phpunit where input parameters are extracted from $_POST

开发者 https://www.devze.com 2023-01-15 15:15 出处:网络
i have stuck at a point for quite some time i have to test a function where the parameters are extracted from the $_POST global array.

i have stuck at a point for quite some time

i have to test a function where the parameters are extracted from the $_POST global array.

look at the following for a better clarification

my function looks like this

function getUsers()
       {

           extract($_POST);
       $usersQry=$this->db->query("select user from user_table where org_type='".$orgType."'")
      开发者_Go百科 return $usersQry;
}

in the above $orgType is an index in $_POST array.

as no parameter is passed to the function getuser() i can not pass parameters as array from the test file.see below

 $testdata=$this->users_model->getUsers($orgType);// i can not go for this option in test file

please post some alternatives and help me to get out of this juncture.

thanks.


Technically there is nothing preventing you from changing $_POST inside your test code, before calling getUsers(). Its just an array. $_POST['orgType'] = something will work.

You may also want to enable backupGlobals, as described here: www.phpunit.de


The code you provided is quite buggy, so it is hard to test.

  1. You are unable to manipulate (e.g. fake, mock) $_POST values outside the method
  2. You allow to set any variable via extract
  3. You pass unvalidated data to SQL query (SQL injection)

Better approach would be:

function getUsers($post = null) 
{
    if (null === $post) {
         $post = $this->getSanitizedPost();
    }

    if (isset($post['orgType']) {
         throw new Exception('Missing required parameter…');
    }

    $orgType = $post['orgType'];
    $usersQry = $this->db->query("select user from user_table where org_type='".$orgType."'");

    return $usersQry;
}
/**
 * Assert exception…
 */
function testHasRequiredParamter() 
{
     $post = array('param1'=>'val1');
     $users = $this->tested->getUsers($post);
     ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消