#19787·yii2

Feature request: aliased fixture dependences

Author: santilinCreated Mar 14, 2023Updated May 29, 2026
Labelstype:feature

What steps will reproduce the problem?

Following example in Testing: fixtures,

I can do:

$profile = $I->grabFixture('profiles', 'user1');

But I can not grab a user which is dependent on profileuser:

$user = $I->grabFixture('user', 'user1');

because I get the error "User fixture not loaded".

To grab a user fixture, I have to do:

$user = $I->grabFixture('tests\fixtures\UserFixture', 'user1');

Which is cumbersome.

If I define dependent fixtures with an alias:

namespace app\tests\fixtures;

use yii\test\ActiveFixture;

class UserProfileFixture extends ActiveFixture
{
    public $modelClass = 'app\models\UserProfile';
    public $depends = [**'user'** => 'app\tests\fixtures\UserFixture'];
}

and add these lines to yii2/test/FixtureTrait.php:

    index cd4bd1431..6a82bec3c 100644
--- a/test/FixtureTrait.php
+++ b/test/FixtureTrait.php
@@ -205,11 +205,14 @@ trait FixtureTrait
                 if (!isset($instances[$name])) {
                     $instances[$name] = false;
                     $stack[] = $fixture = Yii::createObject($fixture);
-                    foreach ($fixture->depends as $dep) {
-                        // need to use the configuration provided in test case
-                        $stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep];
-                    }
-                }
+                                       foreach ($fixture->depends as $alias => $dep) {
+                                               if( is_string($alias) ) {
+                                                       $aliases[$dep] = $alias;
+                                               }
+                                               // need to use the configuration provided in test case
+                                               $stack[] = isset($config[$dep]) ? $config[$dep] : ['class' => $dep];
+                                       }
+                               }
                 // if the fixture is already loaded (ie. a circular dependency or if two fixtures depend on the same fixture) just skip it.

Then I can do

$user = $I->grabFixture('user', 'user1');

By the way, the manual page Testing: fixtures, is misleading as is creating a UserProfileFixture that ends up using the user.php file with user data instead of using a userprofile.php data file with user profile data.

Additional info

Q A
Yii version Yii2.0.48-dev