Using Fixtures For Unit Tests [Solved]

Hi all, I’ve started diving into Yii2 and I’m exploring all of its aspects, and especially tests and testing with CodeCeption.

The problem I’m currently stuck on regards the fixtures in unit tests.

I’ve started following the guide available at http://www.yiiframework.com/doc-2.0/guide-test-fixtures.html

I’m also using the yii-app-base that I’ve installed a couple of months ago.

Because of that I’m currently using a slightly different directory structure compared to the latest commit, which works fine only with Yii-Codeception module version 2.0.0-beta.

To be concrete, I’ve implemented the class UserFixture in tests/unit/fixtures/




namespace app\tests\fixtures;


use yii\test\ActiveFixture;


class UserFixture extends ActiveFixture

{

    public $modelClass = 'app\models\User';

}

and the related user fixture in tests/unit/fixtures/data/user.php:


return [

    'admin' => [

        'id' => 1,

        'username' => 'admin',

        'password' => 'valid password',

        'authkey' => 'valid authkey'

    ]

];



Now in my test I’ve tried to add the following:




namespace tests\unit\models;


use app\models\User;

use app\tests\fixtures\UserFixture;

use yii\codeception\TestCase;

use Yii;


class UserTest extends TestCase

{

    public function fixtures()

    {

        return [

            'user' => UserFixture::className(),

        ];

    }


    protected function setUp()

    {

        parent::setUp();

        // uncomment the following to load fixtures for user table

        $this->loadFixtures(['UserFixture']);

    }



with this if I run the tests I get:


$ vendor/bin/codecept run unit

Codeception PHP Testing Framework v2.0.6

Powered by PHPUnit 4.4-dev by Sebastian Bergmann.


Unit Tests (14) --------------------------------------------------------------------------------------------------------------------------------------------------------------

Trying to test validate returns false if parameters are not set (tests\unit\models\UserTest::testValidateReturnsFalseIfParametersAreNotSet)                              PHP Fatal error:  Class 'app\tests\fixtures\UserFixture' not found in /mnt/workspace/test/yii2composer/basic/tests/unit/models/UserTest.php on line 19

...



I’ve omitted the full stack trace for brevity.

Someone pointed out to me that I might need to include the class manually, but it feels weird to me.

AFAIK there are two cases:

  • the latest version works and I just need to "upgrade"

  • I’m missing something blatantly stupid.

Any idea?

yay! I finally figured out what was wrong:

The namespace of the UserFixture should have been:


namespace app\tests\unit\fixtures;

FYI, in the dev version of the yii2-app-basic it’s going to be


namespace app\tests\codeception\unit\fixtures;

as now the codeception suite and configuration has been reorganised in a more clever and intelligent way.

Now I need to figure out how to use CodeCeption Stubs :P