Search code examples
phpyiiphpunitfixtures

Yii: Fixtures And Setup() In Unit Test


I hope someone can help me. I installed and tried to use phpunit. It Works well but now i tried to use fixtures and the setUp method and it doesn't work.

class RightGroupTest extends CDbTestCase {

    public $fixtures = array(
            'rights' => 'Right',
            'groups' => 'RightGroup',
    );

    public function setUp() {
            $group = new RightGroup($this->groups['group1']);
}

If I execute the test above I get an error message:

Exception: Unknown property 'groups' for class 'RightGroupTest'.

But if I execute this

class RightGroupTest extends CDbTestCase {

    public $fixtures = array(
            'rights' => 'Right',
            'groups' => 'RightGroup',
    );

    public function testIndex234() {

            $group = new RightGroup($this->groups['group1']);
}

everything works.

And a second question:

I have a many to many relationship. For example I can create groups and each group has several rights. Is there a way to create a group with several right objects in a fixture? I already tried soomething like this

return array(
    'group1'=>array(
        'title'=>'Admin',
        'created'=>'2013-05-30',
        'updated'=>'2013-05-30',
        'rights' => array(
            $this->getRecord('right', 'right1'),
            $this->getRecord('right', 'right2'),
            $this->getRecord('right', 'right3'),
        ),
    ),
    'group2'=>array(
        'title'=>'User',
        'created'=>'2013-05-30',
        'updated'=>'2013-05-30',
    ),
);

Solution

  • Fixtures are loaded in CDbTestCase in the setUp() method. So if you want to override this method you should call the parent first:

    public function setUp()
    {
        parent::setUp();
        // use fixtures here
    }
    

    As for your second question: No, you have to create a separate fixture file for every table. The fixture system can't manage related records.