yii controller action unit testing without selenium
Suppose I have an action:
function actionShowItem($id)
{
$item = Item::model()->findByPk($id);
$this->render("showitem",array('model' => $id));
}
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.
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.
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.
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;
}
链接地址: http://www.djcxy.com/p/61262.html
上一篇: 防止在红宝石sinatra会议固定
下一篇: yii控制器动作单元测试不含硒