yii不含硒的控制器动作单元测试 [英] yii controller action unit testing without selenium

查看:73
本文介绍了yii不含硒的控制器动作单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个动作:

function actionShowItem($id)
{
    $item = Item::model()->findByPk($id);
    $this->render("showitem",array('model' => $id));
}

此操作的简单单元测试是什么,它将验证视图输出中的文本.在zend框架中不使用硒即可轻松实现.我们也可以在zend中创建伪造的GET和POST.但是我在Yii中没有找到相同的例子.请提出建议.

What is the simple unit test for this action which will verify text in the view output. Its easy in zend framework without using selenium. We could create fake GET and POST too in zend. But I have not found same examples in Yii. Please suggest.

推荐答案

Yii PHP框架在很多方面都非常出色,但令人遗憾的是它不内部支持任何类型的模拟控制器动作输出测试.它仅具有基于硒的Web浏览器方法.我是从ZendF来到Yii的,而zend确实有很好的测试系统,包括基于xpath的断言.因此,我必须了解代码流,并在我的components/Controller.php中对此进行编码.无需更改任何核心yii框架即可完成此工作,我认为这是Yii的魅力.

The Yii PHP framework is very good in many aspects but its very sad that it does not internally support any sort of simulated controller action output testing. It only has selenium based web browser methods. I came to Yii from ZendF and zend does have good testing systems including xpath based assertions. So I had to understand the code flow and code this within my components/Controller.php. It could be done without changing any core yii framework which in my opinion is the charm of Yii.

每个客户端代码都具有components/Controller.php,这是Yii中所有控制器的通用基类. render是一个CController方法,这意味着我可以重写它并捕获视图输出以供单元测试代码使用.

Every client code has components/Controller.php which is a common base class for all controllers in Yii. And render is a CController method which means I could override it and capture view output for use by the unit test code.

您将需要一个运行模式参数(位于config/main.php中)以标识您是测试运行还是生产运行.在生产中,只是简单地回显了输出,而在测试运行中我们却无法回显任何内容(只是破坏了单元测试报告).在测试代​​码中,您将获得$ render_output的输出,可以在其上声明断言包装器xpath或strpos检查.这种技巧不是最好的,但是做得很好.

You would need a runmode param (in config/main.php) to identify if you are a testrun or a production. In production output is simply echoed while we cannot echo anything in testrun (Just spoils the unit test report). In the test code you get the output in $render_output on which you can do assert wrapper xpath or strpos checks. This hack is not the best but does the job just fine.

function render($view,$data=null,$return=false)
{
    $out = parent::render($view,$data,true);

    if(isset(Yii::app()->params['runmode']) 
       && Yii::app()->params['runmode'] == 'test')
    {
        global $render_output;
        return $render_output = $out;
    }

    if($return)
        return $out;
    else
        echo $out;

}

这篇关于yii不含硒的控制器动作单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆