'YII2 mock web Request class in controller

In my yii2 controller I am running this:

$address = \Yii::$app->request->post('address');

How can I mock this request in PHPUnit? I've tried using mockery but cannot figure out how to mock the \Yii::$app part?



Solution 1:[1]

to mock a request in Yii2 try this

use yii\web\Request;
use Codeception\Stub;

private function  mockRequest($attributes){
    // mock a request
    $_SERVER['REQUEST_URI'] = 'http://localhost';
    $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
    \Yii::$app->requestedAction = new Action('fake', $this->model);
    \Yii::$app->setHomeUrl('http://localhost');
    return Stub::make(Request::class, [
        'getUserIP' =>'127.0.0.1',
        'enableCookieValidation' => false,
        'getUserAgent' => 'Dummy User Agent',
        'getBodyParams' => [
            'MyModel' => $attributes
        ],
    ]);
}

Solution 2:[2]

I struggled quite a bit with this one last week. I'm using Codeception, but I believe this will also work for PHPUnit, only needing minor adjustments.

Create a partial mock of the Request class and set it as active request inside your test:

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

$request->expects($this->any())
        ->method('getIsAjax')
        ->will($this->returnValue(true));

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

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

Source

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 t6nnp6nn
Solution 2 undefined