createController from Module for Tests


(Jonny) #1

Hi

I can’t seem to instantiate a controller within my tests that references a controller in one of my modules.
Web.php

'modules' => [
     ... 
     'console' => [ // module for console
            'class' => 'app\modules\console\Module',
        ],
]

ConsoleCest.php

 public function testCreateLetters(\FunctionalTester $I)
    {
        $controller = \Yii::$app->createController('console');
        codecept_debug(var_dump($controller));
}

I have a module called console that looks like this

- app
    -modules
        -console
            -commands
                -CommandController
       -Module.php

Inside my Module.php I have a createController function

class Module extends \yii\base\Module implements BootstrapInterface
{
    public $controllerNamespace = 'app\modules\console\controllers';

    public function init()
    {
        parent::init();
        // custom initialization code goes here
    }

    public function createController($route)
    {
        return \Yii::$app->createControllerByID('commands');
    }

    public function bootstrap($app)
    {
        if ($app instanceof \yii\console\Application) {
            $this->controllerNamespace = 'app\modules\console\commands';
            // https://github.com/omnilight/yii2-scheduling#how-to-use-this-extension-in-your-own-extension
            if ($app->has('schedule')) {
                /** @var omnilight\scheduling\Schedule $schedule */
                $schedule = $app->get('schedule');
            }
        }
    }
}

But it always returns null when trying ton instantiate the controllers in this module. But if I use return \Yii::$app->createControllerByID('site'), which references app\controllers namespace then it returns the controller. I also tried the full name space and it returned null too.

So I’m not sure what I’m missing here, if anyone could let me know that would be great

Thanks :slight_smile: