CakePHP Unit Test Not Returning Content or View

2019-06-13 17:58发布

问题:

I'm working on implementing test cases for our project to be included in our build script. This CakePHP 2.4 application is largely REST based and has been set to parse json extensions in its routes.php file. Here is an example of a typical function in our application:

public function index() {
    $this->paginate = array(
        'fields' => array('User.username', 'User.first_name', 'User.last_name', 'UserGroup.name','Location.name','User.id'),
        'conditions' => array(
            'active'=>1
        ),
        'link' => array('UserGroup','Location')
    );
    $this->set('response', $this->RestApi->getResponse());
    $this->set('_serialize','response');
}

This would return a json structure like this:

{"sEcho":1,"iTotalRecords":16,"iTotalDisplayRecords":14,"aaData":[["admin","Administrative"],["salesman","Salesman"]]}

So I expected when writing my test cases that in calling this URL I would receive a JSON response, and one of my tests would be to properly decode it and move on with validating the data. Problem is, the call to testAction returns nothing (I'ved tried telling it to return view and contents). The only way I am able to access the response is by looking at the return vars.

Example - Not Working:

$result = $this->testAction('/users/index.json',array(
    'method' => 'GET',
    'return' => 'contents'
));
var_dump($result); // NULL

Example - Is Working:

$result = $this->testAction('/users/index.json',array(
    'method' => 'GET',
    'return' => 'vars'
));

So what's the problem with looking at vars? Well for one its a little further than a real world example of how the application works. It also makes me a little worried about the architecture if I can't get a basic unit test to work as expected.

Please advise and thanks for reading!

EDIT: I should add that even when doing a testAction against a non rest url, such as one that just returns HTML, I still get no response. No HTML etc...

回答1:

I eventually solved this. It was necessary to disable the Auth component. There are some blogs and discussion threads on how to do this within the tests themselves, but it seemed tedious to have to repeat the same code in every test. My solution was to automatically disable the Auth component when tests ran.

In AppController::beforeFilter:

// For Mock Objects and Debug >= 2 allow all (this is for PHPUnit Tests)
if(preg_match('/Mock_/',get_class($this)) && Configure::read('debug') >= 2){
    $this->Auth->allow();
}

I felt this was pretty elegant since we care more about core functionality on deployments. We will likely go back and create a unit test to validate the Auth / ACL components are working as they are supposed to.