Mock Yii2 components

The well written code is also testable code – it is loosely coupled to┬áthe other components, it follows the single responsibility principle, there are no explicit dependencies and so on. We all know the rules, but there is always an exception.

It’s pretty common situation to unit test component or controller that depends on another core Yii component – for example using \yii\web\Request to get query string or $_GET variable.

Rewriting your library in order to remove the explicit dependencies is not always option, because it may lead to massive refactoring and actually break more things than benefits.

In such as case a what I really want to do is to assign temporarily \Yii::$app->request PHPUnit Mock Class, so I can override the return values e.g.

$request = $this->getMock('\yii\web\Request', ['getUserIP', 'getUserAgent', 'getBodyParams']);


 ->will($this->returnValue('Dummy User Agent'));


\Yii::$app->set('request', $request);


One thought on “Mock Yii2 components

  1. TonisOrmisson


    also can be achieved by:

    $request = Stub::make(Request::class, [
    \’getUserIP\’ =>\’\’,
    \’getUserAgent\’ => \’Dummy User Agent\’,
    \’getBodyParams\’ => $this->returnValue([]),

    \\Yii::$app->set(\’request\’, $request);

Comments are closed.