Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel PHPUnit mock Request

I'm doing a PHPUnit on my controller and I can't seem to mock the Request right.

Here's the Controller:

use Illuminate\Http\Request;

public function insert(Request $request)
{
    // ... some codes here
    if ($request->has('username')) {
        $userEmail = $request->get('username');
    } else if ($request->has('email')) {
        $userEmail = $request->get('email');
    }
    // ... some codes here
}

Then on the unit test,

public function testIndex()
{
    // ... some codes here

    $requestParams = [
        'username' => 'test',
        'email'    => '[email protected]'
    ];

    $request = $this->getMockBuilder('Illuminate\Http\Request')
        ->disableOriginalConstructor()
        ->setMethods(['getMethod', 'retrieveItem', 'getRealMethod', 'all', 'getInputSource', 'get', 'has'])
        ->getMock();

    $request->expects($this->any())
        ->method('get')
        ->willReturn($requestParams);

    $request->expects($this->any())
        ->method('has')
        ->willReturn($requestParams);

    $request->expects($this->any())
        ->method('all')
        ->willReturn($requestParams);

    // ... some codes here
}

The problem here is that when ever I var_dump($request->has('username'); it always return the $requestParams value in which is the whole array. I'm expecting that it should return true as the username key exists in the array.

Then when I delete the username key on the $requestParams, it should return false as it does not contain the username key on the array

like image 268
basagabi Avatar asked Sep 22 '17 06:09

basagabi


1 Answers

Its not ideal to mock Requests, but sometimes you just want to do it anyway:

protected function createRequest(
    $method,
    $content,
    $uri = '/test',
    $server = ['CONTENT_TYPE' => 'application/json'],
    $parameters = [],
    $cookies = [],
    $files = []
) {
    $request = new \Illuminate\Http\Request;
    return $request->createFromBase(
        \Symfony\Component\HttpFoundation\Request::create(
            $uri,
            $method,
            $parameters,
            $cookies,
            $files,
            $server,
            $content
        )
    );
}
like image 172
Ian Avatar answered Sep 25 '22 06:09

Ian