Mr.Throg
Mr.Throg

Reputation: 1005

How to write unit test cases for session variables in laravel 5.4

Hello I have a test case which will call a route and it will return some data if the session will set. Here is my test case

class TestControllerTest extends TestCase
{
    // ...

    public function testResponseOfJson()
    {
        $response = $this->call('GET', 'profile/test');
        $this->assertEmpty( !$response );
    }

    // ...
}

and here is my controller

Class TestController{
   public function sendResponse(Request $request){
     $this->data['user_id'] = $this->request->session()->get('userdata.userid'); 
if($this->data['userid']){
   return data;
}
else{ 
   return Failed;
     }
   }
}

My routes.php

Route::get('profile/test',['uses'=>'TestController@sendResponse']);

how can i set the session variable userdata.userid and get while doing unit testing.

Upvotes: 0

Views: 2587

Answers (1)

Julian Camilleri
Julian Camilleri

Reputation: 3105

Please check this page.

Laravel gives you the capability of using withSession chain method and other functions that will help you test where a session is required or needs to be manipulated in some way.

Example:

<?php

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $response = $this->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}

Upvotes: 2

Related Questions