PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] Mock view helper in Yii2 in PHPUnit test

 February 27, 2022     mocking, php, phpunit, yii, yii2     No comments   

Issue

I want to test a specific controller action in Yii2 framework. This action render view file that use helper yii\helpers\Url:

Url::toRoute('page')

When unit test call this view I have error:

yii\base\InvalidArgumentException: Unable to resolve the relative route: vendor/bin/. No active controller is available.

Test:


<?php

use app\modules\user\controllers\UserController;

class UserControllerTest extends \PHPUnit_Framework_TestCase
{
    public function testActionIndex() {

        Yii::configure(Yii::$app, [
            'components' => [
                'user' => [
                    'class' => 'yii\web\User',
                    'identityClass' => 'app\modules\user\models\User',
                ],
                'request' => [
                    'class' => 'yii\web\Request',
                    'cookieValidationKey' => 'abc',
                ],
            ],
        ]);

        $controller = new UserController('user', Yii::$app);
        $result = $controller->run('index', []);
    }
}

How can I mock method Url::toRoute in view to avoid this error?


Solution

Url helper uses Yii::$app->controller for resolving relative routes. You need to set Yii::$app->controller before you call your action:

Yii::$app->controller = new UserController('user', Yii::$app);
$result = Yii::$app->controller->run('index', []);

Alternatively you may avoid this problem using absolute routes:

Url::toRoute('/mymodule/mycontroller/page');

Although it is quite impractical, since you will need to repeat the same route in many places.



Answered By - rob006
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing