UnitTest一个调用模型的PHP CodeIgniter控制器

时间:2016-01-06 08:08:44

标签: php codeigniter unit-testing phpunit

我正在使用PHPUnit测试框架(var methods = assembly.GetTypes() .SelectMany(t => t.GetMethods()) .Where(m => m.GetCustomAttributes(typeof(ParameterAttribute), false).Length > 0) .ToArray(); foreach (var assemblyMethod in methods) { Console.WriteLine(assemblyMethod.Name); // or do other stuff here } )测试我的CodeIgniter项目。当函数CITest.php直接调用模型以获取用户的详细信息时,它可以完美地工作。但是当我通过调用函数test_model()通过控制器执行相同操作时,它不会输出任何内容(当我调试时,模型本身不会被调用)。我甚至通过创建函数test_controller()来验证是否正确传递了帖子数据。我错过了什么吗?

我只能找到直接测试mdoel的在线资源或单独测试控制器。但是我找不到任何有用的链接来调用触发模型的控制器。

CITest.php

test_post_data()

Test_controller.php

class CITest extends PHPUnit_Framework_TestCase
{
  private $CI;
  public function setUp()
  {
    $this->CI = &get_instance();
    $this->CI->load->model('Test_model');
    $this->model = $this->CI->My_model; // load the model
    $this->auth = new Test_controller; // load the controller
  }

  public test_model() {
    $user_id = 6;
    print_r($this->model->getUserData($user_id));
  }

  public test_post_data() {
    $_POST['useR_id'] = 22;
    print_r($this->model->check_post_data());
  }

  public test_controller() {
    $_POST['useR_id'] = 22;
    print_r($this->model->get_user_data());
  }
}

Test_model.php

class Test_controller extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Test_model');
    }

    public function check_post_data() {
        return $this->input->post();
    }

    public function get_user_data() {
        $user_id = $this->input->post('user_id');
        return $this->Test_model->getUserData($user_id);
    }
}

1 个答案:

答案 0 :(得分:0)

CITest.php

中的代码

public test_controller() { $_POST['useR_id'] = 22; print_r($this->model->get_user_data()); }

应该如下?

public test_controller() { $_POST['useR_id'] = 22; print_r($this->auth->get_user_data()); }