1

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'

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.