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']);

$request->expects($this->any())
 ->method('getUserIP')
 ->will($this->returnValue('127.0.0.1'));

$request->expects($this->any())
 ->method('getUserAgent')
 ->will($this->returnValue('Dummy User Agent'));

$request->expects($this->any())
 ->method('getBodyParams')
 ->will($this->returnValue([]));


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

Enjoy!

One thought on “Mock Yii2 components

  1. TonisOrmisson

    Thanks

    also can be achieved by:

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

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

Comments are closed.