douduikai0562
douduikai0562
2012-06-13 21:34
浏览 32
已采纳

Yii - 模块中的功能单元测试时出现CHttpRequest错误

When I'm trying to execute a functional unittest of a module within my Yii code, I keep receiving the following error:

CException: CHttpRequest is unable to determine the request URI.

At first, I though it was because it couldn't find the module. However, If I change the url to a wrong one, I get a correct error,s tating it couldn't find the view.

This is how my testing code looks like

public function testViewControllerModule()
{
    ob_start();
    Yii::app()->runController('module/controller/view');
}

Any ideas on what I might be missing?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsb238100
    dsb238100 2012-06-21 03:03
    已采纳

    I think it's because you haven't set any server variables, i.e $_SERVER and you might be doing something like this in your controller:

    Yii::app()->request ....
    

    So before you run your test, make sure you use a fixture for the server variables also. I think this should suffice for now:

    $_SERVER=array(
        'REQUEST_URI'=>'index.php', // the other fields should follow
    );
    

    However to run functional tests i would recommend using SeleniumRC, you won't have to do these workarounds then, and can simulate user clicks also, i think.

    Read the initial guide to Functional Testing , read the selenium rc phpunit guide, and also the CWebTestCase documentation.

    Notes: You might still have to use fixtures for some variables, and i don't have much experience in testing(which is bad), so i'm not very sure if i am completely correct about selenium.

    点赞 评论
  • douna2633
    douna2633 2013-09-04 19:47

    bool.devs answer works so far.

    This blog post explains the origin of the exception pretty well:
    http://mattmccormick.ca/2012/09/14/unit-testing-url-routes-in-yii-framework/

    In my case, I generalized the solution and have set the following variables in /www/protected/tests/bootstrap.php:

    ...
    
    $_SERVER['SCRIPT_FILENAME'] = 'index-test.php';
    $_SERVER['SCRIPT_NAME'] =  '/index-test.php';
    $_SERVER['REQUEST_URI'] = 'index-test.php';
    
    Yii::createWebApplication($config);
    

    Consider using 'index-test.php' instead of 'index.php' because it contains the config 'test.php' which is responsible for fixtures and maybe other test relevated configurations.

    If someone has better suggestions feel free to comment :)

    Kind regards

    点赞 评论

相关推荐