mardi 12 septembre 2017

Laravel PHPUnit session get

How do I unit test sessions from the Request wherein it will get specific sessions only?

Example: IndexController.php

use Illuminate\Http\Request;

public function index(Request $request)
{
    // some logic here

    $userName = $request->session()->get('userName');

    // some logic here
}

Example: IndexControllerTest.php

public function testIndex()
{
    $request = $this->getMockBuilder('Illuminate\Http\Request')
        ->disableOriginalConstructor()
        ->setMethods(['session'])
        ->getMock();

    $session = $this->getMockBuilder('Illuminate\Session\Store')
        ->disableOriginalConstructor()
        ->setMethods(['get', 'set', 'all'])
        ->getMock();        

    $this->session(['userName' => 'bar']);

    $session->expects($this->any())
        ->method('get')
        ->willReturn($this->app['session']->all());

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

    $this->controller->index($request);
}

public function setUp()
{
    parent::setUp();
    $this->controller = new IndexController();
}

Whenever I var_dump($request) on the controller itself, it returns:

[
  "_token" => "YDtdkCHPPOhNUFVEnofxkIdys3IjQKUJYp2PrwzM"
  "userName" => "bar"
]

In which I expect it to return only bar as I already pass the userName on the get.

So if I get another session, for instance 'emailAddress', then it should return only the value for the emailAddress session.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire