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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With