Question about Unit testing

Hi,

I have a question about unit testing the way it’s done in the book.

Take for example the function actionCreate(), which is used in my controller classes. When writing a unit test for this function, why does the test function testActionCreate() not use the actionCreate() function itself?

It seems to me the function itself is not being tested, but the logic behind it. My collegues and I don’t understand why this is. Since the actual function is not being tested, doesn’t that make the unit test a bit useless?

Unfortunately, when trying to use actionCreate() inside testActionCreate(), it does not work, and I can’t get it working any way I try.

Does anyone know of a way to use the function actionCreate() in the function testActionCreate() ?

Here are both functions:




   /**

     * Creates a new model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     */

    public function actionCreate() 

    {

        $model = new Machine;


        // Uncomment the following line if AJAX validation is needed

        // $this->performAjaxValidation($model);


        if (isset($_POST['Machine'])) {

            $model->attributes = $_POST['Machine'];

            $model->setAttribute('machineCreated', new CDbExpression('NOW()'));

            $model->setAttribute('lastChange', new CDbExpression('NOW()'));

            if ($model->save())

            {    

                $this->redirect(array('view', 'id' => $model->machineSerial));

            }

        }


        $this->render('create', array(

            'model' => $model,

        ));

    }






/**

     * @covers MachineController::actionCreate

     */

    public function testActionCreate() {

        // create new machine

        $newMachine = new Machine;

        $newMachineName = 'Test Machine New';

        $newMachine->setAttributes(

                array(

                    'machineSerial' => 1003,

                    'machineName' => $newMachineName,

                )

            );

        // save the new machine, triggering attribute validation

        $this->assertTrue($newMachine->save());

        //READ back the newly generated machine to ensure the creation worked

        $retrievedMachine = Machine::model()->findByPk($newMachine->machineSerial);

        $this->assertTrue($retrievedMachine instanceof Machine);

        $this->assertEquals($newMachineName, $retrievedMachine->machineName);

    }



In YII unit testing is usually performed on models, components, etc. For controller function testing try Functional tests http://www.yiiframework.com/doc/guide/1.1/en/test.functional