devi
devi

Reputation: 13

PHP UNIT TEST - $_POST returning null values when saving to database

I am very new to php and phpunit test cases. I am trying to write a testcase to save the values into database using $_POST in test case. When I execute the test case, POST is returning null values. Please help how to use $_POST variable in php unit testing.

TEST CLASS-

  public function setUp() {
      $this->resetInstance();
      $this->CI->load->model('save_data_model');
      $this->obj = $this->CI->save_data_model; 
  }  

 public function test_SaveData()
  {              
    $_SERVER['REQUEST_METHOD'] = 'POST';
    $_POST = array('value1'=>'10','value2'=>'100');     
    $actual = $this->obj->SaveData('1');
    $this->assertNotNull($actual);
   }

  }

     MODEL  -

    public function SaveData($id)
    {
        $sql['value1'] = $_POST['js_data']['input_value1'];
        $sql['value2'] = $_POST['js_data']['input_value1'];
        $sql['id'] = $id;

        if(!empty($id))
            {
                $this->db->where('id',$id);

                if($this->db->update('table_name',$sql))
                {
                    return 'Updated';
                }
                else
                {
                    return 'Not Updated';
                }
            }
    }

    Severity: NoticeMessage:  Undefined index: js_dataFilename in SaveData.php
    Database error: A Database Error Occurred

    NULL VALUE FOR value1
    UPDATE `table_name` SET `value1` = NULL, `value2` = NULL
    WHERE `id` = '1'

Upvotes: 1

Views: 631

Answers (1)

otaviofcs
otaviofcs

Reputation: 785

I see you are a phpunit/tests newbie. That's a good thing.

You are setting $_POST['value1'] but you intend to retrieve $_POST['js_data']['input_value1'] in your model.

But, besides that, I can give you a few advices:

1) don't use $_POST in your models 2) declare public variables for the attributes of your models (such as public $value1; public $id;...) 3) then, at your test you should set: $this->obj->value1 = 'xxxx'; ..... 4) afterwards check your output with assertions. SaveData will return a string in the function you wrote. Always. So you should try assertEquals instead 5) you could have assertNotNull as a secondary assertion as your code can change. Test what your code should and what it should not do is a good practice.

BTW, you should try to learn more on what a model stands for. Keep improving.

Upvotes: 1

Related Questions